smb02 A state machine in C IINO pointers - but instead a case switch construction Based on smb01 but with a data struct that is passed to each state smb005.html is based on smb02 buth instead of a case switch a array with function adresses is used Its more compact and I think its easier to expand #include <stdio.h> #include <stdlib.h> #include <unistd.h> // state dft enum states {INIT,LEDON,LEDOFF}; // you just define your need #define MSGARSIZE 4 typedef struct { int data[MSGARSIZE]; } msgTp; // state functions enum states init(msgTp *msg) { printf("\ninit\n"); sleep(1); return LEDON; // return next state } enum states ledOn(msgTp *msg) { printf("\nledOn\n"); sleep(1); return LEDOFF; } enum states ledOff(msgTp *msg) { printf("\nledOff\n"); sleep(1); return LEDON; } int main() { msgTp m; // for getting data to from a state enum states state = INIT; while (1) { switch (state) { case INIT: state = init(&m); break; case LEDON: state = ledOn(&m); break; case LEDOFF: state = ledOff(&m); break; default: state = INIT; } } } /** * case-switch considerations * Finding of the proper case can be carried out * in two ways. * * 1) if (..) else if (..) .. * So if you do have 100 case then in average you * will do 50 if (...) * * 2) if you order your cases in numerical order like * case 0: * ... * break; * case 1: * ... * break; * and so forth * a jump table will be generated you just jump to the right case entry. * so no performance lack even in a case with several 100 entries. * * By using the enum state above we are guaranteed the states are numbered 0,1,2,.. * Then you just need to code our case switch in numerical order. * */ |