Search code examples
c++state-machine

Finite State Machine With Function Pointers


I am learning to use finite-state machines for some tasks but I am having problems navigating my state table and executing the functions to make it a useful system.

Consider my state machine:

state machine
(source: wikimedia.org)

Explanation:
* = Print char to stdout
N = '\n'
S = ' '
A = aA-zZ

The code I started with from Automata-based programming on Wikipedia works for such a simple machine, but I want to modify it so that I can have a more robust state transition table and call functions based off those states.

I've posted working basic code at Pastebin, along with the transtion table style I want to use.

I have not used pointers to functions before so I am not sure how to write the transition functions based off the data received by process_event. Eventually I would like to have a template that allows me to have state in/out & transition in/out functions so I can write complex user menus and even programming algorithms much more efficiently.


Solution

  • Using functions as states is very powerful, but using transition tables is very error prone and painful compared to using recursive functions (function states that return functions). A fantastic implementation for you to consider is the quantum hierarchical statem machine. Although it is only about 1000 lines of code as a base, it has an accompanying book to explain any question you might have about how it works. Very powerful, very fast.