State Machine
A state machine is an object whose next behavior depends on an explicit state. In C that is an enum plus a switch, or a function pointer that you replace as the state changes.
Detailed Explanation
Parsers, protocol handlers, UI flows, and device drivers are state machines whether you name them or not. Naming the states stops you from encoding them as a pile of booleans that can form impossible combinations (connected && connecting).
The data is enum State state and whatever the state owns. The API is event(struct M *m, enum Event e). A switch (m->state) handles legal transitions and rejects the rest. Invalid pairs (CLOSE while INIT) return an error instead of corrupting the object.
A function-pointer machine stores void (*step)(struct M *, enum Event). Each state's function ends by setting m->step to the next state's function. There is no central switch. The compiler will not warn about a missing transition; you test the graph.
Entry and exit actions — close a socket when leaving CONNECTED — belong in the transition, not at every call site. If two events leave CONNECTED, both paths must run the exit action. A helper set_state(m, next) that runs exit/enter is how you keep that honest.
State machines and threads: the state is shared data. A mutex, or confinement to one thread, is required. An event arriving in the middle of a transition is the race that produces impossible states.
Draw the graph. If you cannot, the enum is not the real machine yet. Tables of (state, event) -> next can be data, which is easier to review than a 200-line switch.
Code Examples
#include <stdio.h>
enum State { ST_OFF, ST_ON };
enum Event { EV_TOGGLE };
struct Lamp {
enum State state;
};
static int lamp_event(struct Lamp *l, enum Event e)
{
if (e != EV_TOGGLE) {
return -1;
}
l->state = (l->state == ST_OFF) ? ST_ON : ST_OFF;
return 0;
}
int main(void)
{
struct Lamp l = { ST_OFF };
lamp_event(&l, EV_TOGGLE);
printf("%d\n", l.state == ST_ON); /* prints: 1 */
return 0;
}#include <stdio.h>
struct M;
typedef void (*step_fn)(struct M *, int);
struct M {
step_fn step;
};
static void state_b(struct M *m, int ev);
static void state_a(struct M *m, int ev)
{
(void)ev;
printf("a\n");
m->step = state_b;
}
static void state_b(struct M *m, int ev)
{
(void)m;
(void)ev;
printf("b\n");
}
int main(void)
{
struct M m = { state_a };
m.step(&m, 0); /* prints: a */
m.step(&m, 0); /* prints: b */
return 0;
}Common Gotchas
Two booleans can represent three nonsense states
use one enum.
A function-pointer machine needs every state to set the next pointer
a missing assignment sticks you in the old state.
Forgetting an exit action on one transition leaks a descriptor or a lock
Forgetting an exit action on one transition leaks a descriptor or a lock
Updating `state` from two threads without a lock is a data race and can produce
Updating `state` from two threads without a lock is a data race and can produce a value that is neither enum