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.
What is the main purpose of using a switch-case statement in a simple state machine?
Which of the following is the correct syntax for a switch statement in embedded C?
switch(state) {
case 0:
// code
break;
case 1:
// code
break;
default:
// code
}What will be the output of this code snippet?
int state = 1;
switch(state) {
case 0:
printf("State is zero\n");
break;
case 1:
printf("State is one\n");
break;
default:
printf("Unknown state\n");
}Find the error in this state machine code snippet:
int state = 0;
switch(state) {
case 0:
printf("Start\n");
case 1:
printf("Running\n");
break;
default:
printf("Unknown\n");
}You want to design a simple state machine with three states: INIT (0), PROCESS (1), and DONE (2). The machine should start at INIT, then move to PROCESS, and finally to DONE. Which code snippet correctly updates the state inside the switch-case?
int state = 0;
switch(state) {
case 0:
// Move to PROCESS
state = 1;
break;
case 1:
// Move to DONE
state = 2;
break;
case 2:
// Finished
break;
}Pass the test and this pattern moves unknown