State Machine Patterns
Traffic Light
A traffic light cycles through a fixed set of states.
Traffic Light
traffic_light.c
#include <stdio.h>
enum LightState {
LIGHT_RED,
LIGHT_GREEN,
LIGHT_YELLOW
};
enum LightState nextLight(enum LightState state) {
if (state == LIGHT_RED) {
return LIGHT_GREEN;
}
if (state == LIGHT_GREEN) {
return LIGHT_YELLOW;
}
return LIGHT_RED;
}
int main(void) {
int ticks = ;
enum LightState state = LIGHT_RED;
for (int i = 0; i < ticks; i++) {
state = nextLight(state);
}
printf("ticks=%d light=%d\n", ticks, state);
return 0;
}
#include <stdio.h>
enum LightState {
LIGHT_RED,
LIGHT_GREEN,
LIGHT_YELLOW
};
enum LightState nextLight(enum LightState state) {
if (state == LIGHT_RED) {
return LIGHT_GREEN;
}
if (state == LIGHT_GREEN) {
return LIGHT_YELLOW;
}
return LIGHT_RED;
}
int main(void) {
int ticks = ;
enum LightState state = LIGHT_RED;
for (int i = 0; i < ticks; i++) {
state = nextLight(state);
}
printf("ticks=%d light=%d\n", ticks, state);
return 0;
}
#include <stdio.h>
enum LightState {
LIGHT_RED,
LIGHT_GREEN,
LIGHT_YELLOW
};
enum LightState nextLight(enum LightState state) {
if (state == LIGHT_RED) {
return LIGHT_GREEN;
}
if (state == LIGHT_GREEN) {
return LIGHT_YELLOW;
}
return LIGHT_RED;
}
int main(void) {
int ticks = ;
enum LightState state = LIGHT_RED;
for (int i = 0; i < ticks; i++) {
state = nextLight(state);
}
printf("ticks=%d light=%d\n", ticks, state);
return 0;
}
cycle
A cycle returns to the first state after the final state.
transition
The transition helper keeps the next-state rule separate from the loop.