Friday, 22 April 2016

Creating a finite state machine in C language




 Finite state machine implementation in C


This is an implementation of FSM in C as you can see there are 3 functions named
cheese_day(),grapes_day() & lettuce_day() which represents the state/nodes
fsm is an array of pointers to function, which is used to access the functions

i.e. void (*fsm[])()= { cheese_day , grapes_day, lettuce_day };Now we are using the index of the fsm to jump to the specific function
i.e. fsm[input_symbol]();





  1. #include <cstdio>
  2. #include <cstdlib>
  3. #include <cstring>
  4. #define IM_STARVING 0
  5. #define LETS_GO_SHOPPING 0
  6. #define ILL_HAVE_CHEESE_TOMMORROW 1
  7. #define ILL_HAVE_LETTUCE_TOMMORROW 2
  8. #define ILL_HAVE_GRAPES_TOMMORROW 3
  9. int inp[5]= {ILL_HAVE_CHEESE_TOMMORROW ,ILL_HAVE_LETTUCE_TOMMORROW,ILL_HAVE_CHEESE_TOMMORROW,ILL_HAVE_GRAPES_TOMMORROW,IM_STARVING};  // automated Input!
  10. void cheese_day()
  11. {
  12.   printf("state :- cheese day\n");
  13. }
  14. void grapes_day()
  15. {
  16.   printf("state :- grapes day\n");
  17. }
  18. void lettuce_day()
  19. {
  20.   printf("state :- lettuce day\n");
  21. }
  22. void (*fsm[])()= { cheese_day , grapes_day, lettuce_day };
  23. int main()
  24. { int j=0;
  25.   while(j< 5)
  26.   { int input_symbol=inp[j++];
  27.    switch(input_symbol) {
  28.     case 1:
  29.     input_symbol=ILL_HAVE_CHEESE_TOMMORROW - 1;
  30.     fsm[input_symbol]();
  31.     break;
  32.     case 2:
  33.     input_symbol=ILL_HAVE_LETTUCE_TOMMORROW - 1;
  34.     fsm[input_symbol]();
  35.     break;
  36.     case 3:
  37.     input_symbol=ILL_HAVE_GRAPES_TOMMORROW - 1;
  38.     fsm[input_symbol]();
  39.     break;
  40.     default:
  41.     fsm[input_symbol]();
  42.    }
  43.   }
  44.  return 0;
  45. }