DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Simple Finite State Machine In C
I'm vaguely plotting a finite state machine -> C compiler (as toy code, not for a serious project - I know there are plenty already out there), so thought I'd write a sample one by hand to see how it should look. Here's the code for it.
This checks if stdin contains the phrase 'foo' or 'bar'
#include <stdio.h>
main()
{
int c;
START:
switch(c = getchar()){
case 'f' : goto F;
case 'b' : goto B;
case EOF : goto FAIL;
default: goto START; }
F:
switch(c = getchar()){
case 'o' : goto FO;
case EOF : goto FAIL;
default : goto START;}
FO:
switch(c = getchar()){
case 'o' : goto SUCCESS;
case EOF : goto FAIL;
default : goto START;}
B:
switch(c = getchar()){
case 'a' : goto BA;
case EOF : goto FAIL;
default : goto START;}
BA:
switch(c = getchar()){
case 'r' : goto SUCCESS;
case EOF : goto FAIL;
default : goto START;}
FAIL:
printf("Does not match.\n");
return;
SUCCESS:
printf("Matches.\n");
return;
}





