FSM in C are often implemented through loop (while or for), switch and control variables.
This approach has the biggest disadvantage that is almost impossible from the code to understand the original FSM diagram.
That's why c-libutl offers simple macros to implement FSM with a 1-to-1 relationship with the original diagram.
I'm pretty sure you will immediately relate this code:
to this diagram:

The C code for the fsm macros is extremely simple:
This approach has the biggest disadvantage that is almost impossible from the code to understand the original FSM diagram.
That's why c-libutl offers simple macros to implement FSM with a 1-to-1 relationship with the original diagram.
I'm pretty sure you will immediately relate this code:
fsm {
fsmSTATE(S1) {
printf("S1: %d\n",x);
x++;
if (x > 3) fsmGOTO(S2);
fsmGOTO(S1);
}
fsmSTATE(S3) {
printf("S3: %d\n",x);
x++;
if (x > 9) fsmGOTO(exit);
fsmGOTO(S3);
}
fsmSTATE(S2) {
printf("S2: %d\n",x);
x++;
if (x > 6) fsmGOTO(S3);
fsmGOTO(S2);
}
fsmSTATE(exit) {
}
}
to this diagram:

The C code for the fsm macros is extremely simple:
#define fsm #define fsmGOTO(x) goto fsm_state_##x #define fsmSTATE(x) fsm_state_##x : #define fsmSTARTThis simple technique was explained by Tim Cooper in the the article [*Goto? Yes Goto!*](http://ftp.math.utah.edu/pub/tex/bib/complang.html#Cooper:1991:GYG) published on the May 1991 issue of the *Computer Language* magazine and, since then, I've found many uses for it.
Adding exception handling in C is a rather controversial topic. Some think that exceptions are pure evil and should never be considered, others say that those wanting to use exceptions should leave the realm of pure C and fly to C++ (or, even, Java). Others suggest that goto is a perfectly fine way to deal with exceptions.