State machine patterns in C
Switch, transition tables and state-function pointers compared.
Three ways to write the same machine
The same state machine can be written in C in three common styles. Each has a place; interviewers like to ask which you would choose and why. All three below implement a door controller:
CLOSED --open--> OPEN
OPEN --close--> CLOSED
CLOSED --lock--> LOCKED
LOCKED --unlock / beep--> CLOSED
1. Nested switch
The outer switch selects the state, the inner one (or if chain) selects the event.
#include <stdio.h>
typedef enum { CLOSED, OPEN, LOCKED, NUM_STATES } state_t;
typedef enum { EV_OPEN, EV_CLOSE, EV_LOCK, EV_UNLOCK, NUM_EVENTS } event_t;
static const char *const names[] = { "CLOSED", "OPEN", "LOCKED" };
static state_t door_switch(state_t s, event_t e) {
switch (s) {
case CLOSED:
switch (e) {
case EV_OPEN: return OPEN;
case EV_LOCK: return LOCKED;
default: return s;
}
case OPEN:
return e == EV_CLOSE ? CLOSED : s;
case LOCKED:
if (e == EV_UNLOCK) { printf(" (beep)\n"); return CLOSED; }
return s;
default:
return s;
}
}
int main(void) {
event_t script[] = { EV_LOCK, EV_OPEN, EV_UNLOCK, EV_OPEN, EV_LOCK, EV_CLOSE };
state_t s = CLOSED;
for (int i = 0; i < 6; i++) { s = door_switch(s, script[i]); printf("event %d -> %s\n", script[i], names[s]); }
return 0;
}
| Pros | Cons |
|---|---|
| Obvious; easy to read for small machines | Grows long and repetitive |
| Guards and actions are plain code | The structure of the machine is hidden in code |
Compiler warns about unhandled enum values with -Wswitch-enum | Easy to forget a case in a big machine |
Best for: small machines (up to about 5 to 8 states), and machines with complex guards.
2. Transition table
The machine is data: a table of { state, event, next state, action } rows, or a 2-D array indexed by state and event. A generic engine looks up the row and runs it.
#include <stdio.h>
#include <stddef.h>
typedef enum { CLOSED, OPEN, LOCKED, NUM_STATES } state_t;
typedef enum { EV_OPEN, EV_CLOSE, EV_LOCK, EV_UNLOCK, NUM_EVENTS } event_t;
static const char *const names[] = { "CLOSED", "OPEN", "LOCKED" };
typedef void (*action_t)(void);
static void beep(void) { printf(" (beep)\n"); }
typedef struct { state_t next; action_t action; } cell_t;
/* table[state][event]; a cell whose next equals its own state is an ignored event */
static const cell_t table[NUM_STATES][NUM_EVENTS] = {
/* EV_OPEN EV_CLOSE EV_LOCK EV_UNLOCK */
[CLOSED] = { { OPEN, NULL }, { CLOSED, NULL }, { LOCKED, NULL }, { CLOSED, NULL } },
[OPEN] = { { OPEN, NULL }, { CLOSED, NULL }, { OPEN, NULL }, { OPEN, NULL } },
[LOCKED] = { { LOCKED, NULL }, { LOCKED, NULL }, { LOCKED, NULL }, { CLOSED, beep } },
};
static state_t door_table(state_t s, event_t e) {
const cell_t *c = &table[s][e];
if (c->action) c->action();
return c->next;
}
int main(void) {
event_t script[] = { EV_LOCK, EV_OPEN, EV_UNLOCK, EV_OPEN, EV_LOCK, EV_CLOSE };
state_t s = CLOSED;
for (int i = 0; i < 6; i++) { s = door_table(s, script[i]); printf("event %d -> %s\n", script[i], names[s]); }
return 0;
}
| Pros | Cons |
|---|---|
| The whole machine is visible at a glance | Guards need extra columns or functions |
| Every state-event pair must be filled in: nothing forgotten | A 2-D table is sparse and large for many states and events |
| Table in flash; engine is tiny and testable | Actions are separate functions, so logic is spread out |
| Can be generated from a diagram or spreadsheet | Debugging means reading data, not stepping code |
Best for: protocol parsers, machines with many states and few guards, and machines generated by tools. A sparse list of rows ({ state, event, guard, action, next }) searched linearly suits machines where most events are ignored.
3. State functions (function pointers)
Each state is a function that handles events; the current state is a pointer to that function. A transition assigns the pointer.
#include <stdio.h>
typedef enum { EV_OPEN, EV_CLOSE, EV_LOCK, EV_UNLOCK } event_t;
typedef struct door door_t;
typedef void (*state_fn)(door_t *d, event_t e);
struct door { state_fn state; const char *name; int beeps; };
static void st_closed(door_t *d, event_t e);
static void st_open(door_t *d, event_t e);
static void st_locked(door_t *d, event_t e);
static void go(door_t *d, state_fn s, const char *name) { d->state = s; d->name = name; }
static void st_closed(door_t *d, event_t e) {
if (e == EV_OPEN) go(d, st_open, "OPEN");
else if (e == EV_LOCK) go(d, st_locked, "LOCKED");
}
static void st_open(door_t *d, event_t e) {
if (e == EV_CLOSE) go(d, st_closed, "CLOSED");
}
static void st_locked(door_t *d, event_t e) {
if (e == EV_UNLOCK) { d->beeps++; printf(" (beep)\n"); go(d, st_closed, "CLOSED"); }
}
int main(void) {
door_t door = { 0 };
go(&door, st_closed, "CLOSED");
event_t script[] = { EV_LOCK, EV_OPEN, EV_UNLOCK, EV_OPEN, EV_LOCK, EV_CLOSE };
for (int i = 0; i < 6; i++) { door.state(&door, script[i]); printf("event %d -> %s\n", script[i], door.name); }
printf("beeped %d time(s)\n", door.beeps);
return 0;
}
| Pros | Cons |
|---|---|
| Each state's behaviour is together in one function | The overall transition structure is spread across functions |
| No central switch to grow; adding a state adds a function | Function pointers are harder to inspect in a debugger (store a name or ID too) |
Entry and exit actions fit naturally (send ENTRY/EXIT events) | A corrupted pointer jumps anywhere: validate it in safety code |
| Basis of frameworks such as QP |
Best for: medium to large event-driven machines, active objects, and hierarchical machines.
Entry and exit actions
All three styles benefit from a single transition() helper that runs the old state's exit action, changes the state and runs the new state's entry action. That guarantees, for example, that leaving HEATING always switches the heater off, however it is left.
static void transition(door_t *d, state_fn next) {
d->state(d, EV_EXIT);
d->state = next;
d->state(d, EV_ENTRY);
}
Keep the transition logic pure
Whichever form you choose, keep the decision of which state comes next free of I/O where you can. A pure function, next = step(state, event), can be unit-tested on a PC with every state and event combination, and the actions (switching outputs, sending messages) live in entry, exit and transition actions that a test can replace. That is how the practice problems test the state machines you write.
Choosing
| Machine | Style |
|---|---|
| A handful of states, complex conditions | Switch |
| Many states and events, regular structure, parsers | Table |
| Event-driven, entry/exit actions, growing over time | State functions |
| Deep nesting of common behaviour | State functions with hierarchy (see hierarchical state machines) |
Pitfall: A machine with no default case leaves an unexpected event, or a corrupted state value, to chance. Every
switchon a state has adefaultthat goes to a fault state or logs the event deliberately.
Pitfall: In the table style, an action that itself changes the state variable fights with the engine's assignment of
next. Let only the engine change the state; actions only produce outputs or post events.
Interview question: Compare switch-based, table-driven and function-pointer state machines in C.
Answer: A switch is the simplest and keeps guards and actions as ordinary code, but becomes long and hides the structure in large machines. A table puts the whole machine in data, forces a decision for every state-event pair, lives in flash with a tiny generic engine and can be generated by tools, but guards and actions are awkward and spread out. State functions group each state's behaviour in one function, handle entry and exit naturally and scale well for event-driven designs and hierarchy, but the global structure is less visible and debugging pointers needs care. Choose by size, regularity and how event-driven the machine is.
Interview question: How do you guarantee an exit action always runs when a state is left?
Answer: Route every state change through a single transition function that first calls the current state's exit handler, then updates the state variable, then calls the new state's entry handler. No other code assigns the state variable directly. In table-driven designs, store per-state entry and exit function pointers that the engine calls around each change. This ensures, for example, a heater or motor is always switched off when its state is left, whatever event caused it.
Build it: switch the power safely on every transition
This is step 2 of the module project. The transition function from step 1 decides; now each change of state has to drive the hardware: the main contactor that connects the car to the grid, the solenoid that locks the plug in the socket, and the red fault lamp. The order of those actions is a safety requirement.
Lab: Entry and exit actions in the right order
The outputs are on GPIOA, already configured, with helpers that drive them: contactor(on) on PA5, plug_lock(on) on PA6 and fault_lamp(on) on PA7. Step 1's next_state() is provided.
Write charger_dispatch(e). It works out the next state. If the state changes, it runs the exit actions of the old state, then the entry actions of the new one, then remembers the new state. Nothing runs for an ignored event.
| State | On entry | On exit |
|---|---|---|
ST_CHARGING | lock the plug, then close the contactor | open the contactor, then unlock the plug |
ST_FAULT | open the contactor and unlock the plug (both, even if already so), then light the fault lamp | turn the fault lamp off |
| others | nothing | nothing |
Locking before power on, and power off before unlocking, means the plug can never be pulled out of a live socket: unplugging under load draws an arc that can burn the driver.
Every pin change shows up in the output, such as gpioa: pin 5 high (contactor closed).
Going deeper
Interview question: How would you implement a coffee machine's controller in C?
Answer: A table-driven state machine: states (idle, heating, ready, grinding, brewing, descaling, error) and events (button, temperature reached, timer, water low), with a transition table naming each next state and action. The heater's safety limits are checked in every state, and error is reachable from all of them. Tables are easy to review and test exhaustively.
Interview question: How can a table-driven state machine handle guards?
Answer: Store transitions as rows of {state, event, guard function, action function, next state}; the engine scans the rows for the current state and event in order and takes the first row whose guard returns true (a NULL guard means always). Ordering rows from most to least specific gives the right priority. This keeps the table declarative while supporting conditions such as retry limits.
Interview question: How do you make a function-pointer state machine debuggable?
Answer: Store a state name or ID alongside the function pointer (or derive it from a lookup table of handlers) and log every transition with the old state, event and new state. In the debugger, the pointer's value can be mapped to the function name with the symbol table, and a 'current state name' variable makes inspection immediate. Validate the pointer against the known handlers in safety-critical code.
Explain it: In your own words, compare the switch, table and function-pointer ways of writing a state machine in C.
Answer: A switch statement puts the logic for each state in a case and is the simplest and easiest to debug, but grows long and hides the structure as states are added. A transition table puts the whole machine in data indexed by state and event, so every combination is visible and decided, it lives in flash and can be generated by tools, but conditions and actions are more awkward. State functions give each state its own function and store a pointer to the current one, keeping each state's behaviour together and scaling well for event-driven designs, at the cost of a less visible overall structure.