Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 421893
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T19:01:40+00:00 2026-05-12T19:01:40+00:00

I am crafting a small project in mixed C and C++. I am building

  • 0

I am crafting a small project in mixed C and C++. I am building one small-ish state-machine at the heart of one of my worker thread.

I was wondering if you gurus on SO would share your state-machine design techniques.

NOTE: I am primarily after tried & tested implementation techniques.

UPDATED: Based on all the great input gathered on SO, I’ve settled on this architecture:

An event pump points to an event integrator which points to a dispatcher. The dispatcher points to 1 through n actions which point back to the event integrator. A transition table with wildcards points to the dispatcher.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T19:01:40+00:00Added an answer on May 12, 2026 at 7:01 pm

    State machines that I’ve designed before (C, not C++) have all come down to a struct array and a loop. The structure basically consists of a state and event (for look-up) and a function that returns the new state, something like:

    typedef struct {
        int st;
        int ev;
        int (*fn)(void);
    } tTransition;
    

    Then you define your states and events with simple defines (the ANY ones are special markers, see below):

    #define ST_ANY              -1
    #define ST_INIT              0
    #define ST_ERROR             1
    #define ST_TERM              2
    : :
    #define EV_ANY              -1
    #define EV_KEYPRESS       5000
    #define EV_MOUSEMOVE      5001
    

    Then you define all the functions that are called by the transitions:

    static int GotKey (void) { ... };
    static int FsmError (void) { ... };
    

    All these function are written to take no variables and return the new state for the state machine. In this example global variables are used for passing any information into the state functions where necessary.

    Using globals isn’t as bad as it sounds since the FSM is usually locked up inside a single compilation unit and all variables are static to that unit (which is why I used quotes around “global” above – they’re more shared within the FSM, than truly global). As with all globals, it requires care.

    The transitions array then defines all possible transitions and the functions that get called for those transitions (including the catch-all last one):

    tTransition trans[] = {
        { ST_INIT, EV_KEYPRESS, &GotKey},
        : :
        { ST_ANY, EV_ANY, &FsmError}
    };
    #define TRANS_COUNT (sizeof(trans)/sizeof(*trans))
    

    What that means is: if you’re in the ST_INIT state and you receive the EV_KEYPRESS event, make a call to GotKey.

    The workings of the FSM then become a relatively simple loop:

    state = ST_INIT;
    while (state != ST_TERM) {
        event = GetNextEvent();
        for (i = 0; i < TRANS_COUNT; i++) {
            if ((state == trans[i].st) || (ST_ANY == trans[i].st)) {
                if ((event == trans[i].ev) || (EV_ANY == trans[i].ev)) {
                    state = (trans[i].fn)();
                    break;
                }
            }
        }
    }
    

    As alluded to above, note the use of ST_ANY as wild-cards, allowing an event to call a function no matter the current state. EV_ANY also works similarly, allowing any event at a specific state to call a function.

    It can also guarantee that, if you reach the end of the transitions array, you get an error stating your FSM hasn’t been built correctly (by using the ST_ANY/EV_ANY combination.

    I’ve used code similar for this on a great many communications projects, such as an early implementation of communications stacks and protocols for embedded systems. The big advantage was its simplicity and relative ease in changing the transitions array.

    I’ve no doubt there will be higher-level abstractions which may be more suitable nowadays but I suspect they’ll all boil down to this same sort of structure.


    And, as ldog states in a comment, you can avoid the globals altogether by passing a structure pointer to all functions (and using that in the event loop). This will allow multiple state machines to run side-by-side without interference.

    Just create a structure type which holds the machine-specific data (state at a bare minimum) and use that instead of the globals.

    The reason I’ve rarely done that is simply because most of the state machines I’ve written have been singleton types (one-off, at-process-start, configuration file reading for example), not needing to run more than one instance. But it has value if you need to run more than one.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am crating one small module in Spring+Hibernate framework. In my jsp page, on
I bought Crafting Rails Applications this weekend and noticed that the author uses bundle
I have been crafting a makefile for a while now. It supports easy creation
I'm reading a book Crafting Rails Applications by Jose Valim and have come across
So I've got a function that really helps when I'm crafting device specific URLS
I use HTTPS, but want to minimize the risk of someone evil crafting their
Just wondering if requiring a hashed PHPSESSID to be sent to all forms or
Every now and then, as I am dutifully crafting a nice, descriptive commit message
After reading the excellent SO post , I tried crafting a module level metaclass:
I have drawn usecase, activity and class diagrams for Crafting System for my game.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.