Concept Flow - Simple state machine with switch-case
Start
Current State
switch-case on State
State A
Action
Update State
Loop back to Current State
The program checks the current state, runs code for that state, updates the state, and repeats.
enum State {STATE_A, STATE_B, STATE_C};
enum State current = STATE_A;
switch(current) {
case STATE_A: current = STATE_B; break;
case STATE_B: current = STATE_C; break;
case STATE_C: current = STATE_A; break;
}| Step | Current State | switch-case branch | Action | Next State |
|---|---|---|---|---|
| 1 | STATE_A | case STATE_A | Set current = STATE_B | STATE_B |
| 2 | STATE_B | case STATE_B | Set current = STATE_C | STATE_C |
| 3 | STATE_C | case STATE_C | Set current = STATE_A | STATE_A |
| 4 | STATE_A | case STATE_A | Set current = STATE_B | STATE_B |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 |
|---|---|---|---|---|---|
| current | STATE_A | STATE_B | STATE_C | STATE_A | STATE_B |
Simple state machine uses a variable to track state. Use switch-case to run code based on current state. Each case updates the state variable. Use break to prevent fall-through. Loop to cycle through states repeatedly.