State machines in C

前端 未结 9 1721
一整个雨季
一整个雨季 2021-01-30 07:34

What is the best way to write a state machine in C?
I usually write a big switch-case statement in a for(;;), with callbacks to re-enter the state machine when an external

相关标签:
9条回答
  • 2021-01-30 08:24

    Switch statements are a good way to get started, but they tend to get unwieldy when the FSM gets larger.

    A couple related (or duplicate) SO questions with great information and ideas:

    • state machines tutorials
    • C state-machine design
    0 讨论(0)
  • 2021-01-30 08:26

    That's pretty much the standard approach. If you're interested in studying a well considered library and comparing specifics, take a look at Ragel:

    Ragel compiles executable finite state machines from regular languages. Ragel targets C, C++, Objective-C, D, Java and Ruby. Ragel state machines can not only recognize byte sequences as regular expression machines do, but can also execute code at arbitrary points in the recognition of a regular language. Code embedding is done using inline operators that do not disrupt the regular language syntax.

    0 讨论(0)
  • 2021-01-30 08:26

    I use function pointers and a 2d look-up table where I use the state for one parameter and the event as the other.

    I use excel (or any spreadsheet tool) to map a function to every state/event combination.

    When an event occurs, I que it up, so then I have something that looks like this

    int main(void)
    {
        StateList currentState = start_up;
        EventList currentEvent;
    
        uint8_t stateArray[STATE_COUNT][EVENT_COUNT];
    
        InitializeStateArray(stateArray);
        InitializeEventQue();
    
        while(1)
        {
            currentEvent = GetPriorityEvent();
            currentState = (StateList)(*(stateArray[currentState][currentEvent]))();
        }
        return 1;  //should never get here
    }
    

    This method essentially forces the developer to consider all possible events in each state, and in my experience makes debugging a little easier.

    0 讨论(0)
提交回复
热议问题