Over a million developers have joined DZone.

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 

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;
}


Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}