News for hackers. Stuff that matters.
Re:Facts about State Machines by Joker_vD on Friday September 30, 2022 @07:35PM (#33042095)

    typedef struct State State, *StateMachine;
    typedef void (*Event)(StateMachine *sm);

    struct State {
        Event TurnOn;
        Event TurnOff;
        Event MakeStuck;
    };

    void IdleTransition(StateMachine *sm);
    void BecomeOn(StateMachine *sm);
    void BecomeOff(StateMachine *sm);
    void BecomeStuck(StateMachine *sm);

    const State StateOn = {
        .TurnOn    = IdleTransition,
        .TurnOff   = BecomeOff,
        .MakeStuck = BecomeStuck
    };

    const State StateOff = {
        .TurnOn    = BecomeOn,
        .TurnOff   = IdleTransition,
        .MakeStuck = BecomeStuck
    };

    const State StateStuck = {
        .TurnOn    = IdleTransition,
        .TurnOff   = IdleTransition,
        .MakeStuck = IdleTransition
    };

    void IdleTransition(StateMachine *sm)  { }
    void BecomeOn(StateMachine *sm)        { *sm = &StateOn; }
    void BecomeOff(StateMachine *sm)       { *sm = &StateOff; }
    void BecomeStuck(StateMachine *sm)     { *sm = &StateStuck; }

    StateMachine sm = &StateOff;
It's still C but arguably much more concise than a switch, wouldn't you agree?
Re:Facts about State Machines by rowanG077 on Saturday October 01, 2022 @07:37AM (#33045821)
For large state machines sure. For smaller ones no. My point wasn't that enum is the only way to do it in C. Just a simple representation that is used in practice that I could explain in a single sentence.