Saturday, June 23, 2012

Finite State Machines in C

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:

  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 fsmSTART      
This 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.

0 comments :

Post a Comment