Never been to DZone Snippets before?

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

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

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'

   1  
   2  #include <stdio.h>
   3  
   4  main()
   5  {
   6      int c;
   7  
   8      START: 
   9          switch(c = getchar()){
  10              case 'f' : goto F;
  11              case 'b' : goto B;
  12              case EOF : goto FAIL;
  13              default: goto START; }
  14  
  15      F:
  16          switch(c = getchar()){
  17              case 'o' : goto FO;
  18              case EOF : goto FAIL;
  19              default  : goto START;}
  20      
  21      FO:
  22          switch(c = getchar()){
  23              case 'o' : goto SUCCESS;
  24              case EOF : goto FAIL;
  25              default  : goto START;}
  26  
  27      B:
  28          switch(c = getchar()){
  29              case 'a' : goto BA;
  30              case EOF : goto FAIL;
  31              default  : goto START;}
  32  
  33      BA:
  34          switch(c = getchar()){
  35              case 'r' : goto SUCCESS;
  36              case EOF : goto FAIL;
  37              default  : goto START;}
  38  
  39      FAIL: 
  40          printf("Does not match.\n");
  41          return;
  42      SUCCESS:
  43          printf("Matches.\n");
  44          return;
  45  }
  46  
  47  
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS