3 ms·
typedef struct State State, *StateMachine; typedef void (*Event)(StateMachine *sm); struct State { Event TurnOn; Event TurnOff;
by Joker_vD 4y ago
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?
- rowanG077 4y agoFor 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.