smb01 A state machine in C

NO pointers - but instead a case switch construction

raw smb01.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

// state dft

enum states {INIT,LEDON,LEDOFF};


// state functions

enum states init(void)
{
	printf("\ninit\n");
	sleep(1);
	return LEDON; // return next state
}


enum states ledOn(void)
{
	printf("\nledOn\n");

	sleep(1);

	return LEDOFF;
}

enum states ledOff(void)
{
	printf("\nledOff\n");

	sleep(1);

	return LEDON;
}

int main()
{
	enum states state = INIT;

	while (1) {
		switch (state) {
			case INIT:
				state = init();
				break;
			case LEDON:
				state = ledOn();
				break;
			case LEDOFF:
				state = ledOff();
				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.
 *
 */