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

Snippets has posted 5883 posts at DZone. View Full User Profile

Simple Finite State Machine In C

04.10.2007
| 28864 views |
  • submit to reddit
        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;
}