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]();

- #include <cstdio>
- #include <cstdlib>
- #include <cstring>
- #define IM_STARVING 0
- #define LETS_GO_SHOPPING 0
- #define ILL_HAVE_CHEESE_TOMMORROW 1
- #define ILL_HAVE_LETTUCE_TOMMORROW 2
- #define ILL_HAVE_GRAPES_TOMMORROW 3
- int inp[5]= {ILL_HAVE_CHEESE_TOMMORROW ,ILL_HAVE_LETTUCE_TOMMORROW,ILL_HAVE_CHEESE_TOMMORROW,ILL_HAVE_GRAPES_TOMMORROW,IM_STARVING}; // automated Input!
- void cheese_day()
- {
- printf("state :- cheese day\n");
- }
- void grapes_day()
- {
- printf("state :- grapes day\n");
- }
- void lettuce_day()
- {
- printf("state :- lettuce day\n");
- }
- void (*fsm[])()= { cheese_day , grapes_day, lettuce_day };
- int main()
- { int j=0;
- while(j< 5)
- { int input_symbol=inp[j++];
- switch(input_symbol) {
- case 1:
- input_symbol=ILL_HAVE_CHEESE_TOMMORROW - 1;
- fsm[input_symbol]();
- break;
- case 2:
- input_symbol=ILL_HAVE_LETTUCE_TOMMORROW - 1;
- fsm[input_symbol]();
- break;
- case 3:
- input_symbol=ILL_HAVE_GRAPES_TOMMORROW - 1;
- fsm[input_symbol]();
- break;
- default:
- fsm[input_symbol]();
- }
- }
- return 0;
- }