You might have seen my answer to another C question where I mentioned FSM! Here is how I do it:
FSM {
STATE(x) {
...
NEXTSTATE(y);
}
STATE(y) {
...
if (x == 0)
NEXTSTATE(y);
else
NEXTSTATE(x);
}
}
With the following macros defined
#define FSM
#define STATE(x) s_##x :
#define NEXTSTATE(x) goto s_##x
This can be modified to suit the specific case. For example, you may have a file FSMFILE
that you want to drive your FSM, so you could incorporate the action of reading next char into the the macro itself:
#define FSM
#define STATE(x) s_##x : FSMCHR = fgetc(FSMFILE); sn_##x :
#define NEXTSTATE(x) goto s_##x
#define NEXTSTATE_NR(x) goto sn_##x
now you have two types of transitions: one goes to a state and read a new character, the other goes to a state without consuming any input.
You can also automate the handling of EOF with something like:
#define STATE(x) s_##x : if ((FSMCHR = fgetc(FSMFILE) == EOF)\
goto sx_endfsm;\
sn_##x :
#define ENDFSM sx_endfsm:
The good thing of this approach is that you can directly translate a state diagram you draw into working code and, conversely, you can easily draw a state diagram from the code.
In other techniques for implementing FSM the structure of the transitions is buried in control structures (while, if, switch ...) and controlled by variables value (tipically a state
variable) and it may be a complex task to relate the nice diagram to a convoluted code.
I learned this technique from an article appeared on the great "Computer Language" magazine that, unfortunately, is no longer published.