What is the output of this embedded C code simulating a simple protocol state machine?
#include <stdio.h> typedef enum {IDLE, WAIT_ACK, DONE} State; int main() { State current_state = IDLE; int event = 1; // 1 means send request switch(current_state) { case IDLE: if(event == 1) { printf("Request sent\n"); current_state = WAIT_ACK; } break; case WAIT_ACK: printf("Waiting for ACK\n"); current_state = DONE; break; case DONE: printf("Protocol complete\n"); break; } return 0; }
Look at the initial state and which case runs first.
The initial state is IDLE. The event is 1, so it prints "Request sent" and changes state to WAIT_ACK. But the switch only runs once, so only "Request sent" is printed.
What is the value of count after running this code?
#include <stdio.h> typedef enum {START, PROCESS, END} State; int main() { State s = START; int count = 0; while(s != END) { switch(s) { case START: count++; s = PROCESS; break; case PROCESS: count += 2; s = END; break; default: break; } } printf("%d\n", count); return 0; }
Count how many times the loop runs and what increments happen.
The loop runs twice: once in START adding 1, then in PROCESS adding 2. Total is 3.
What error does this code produce when compiled?
#include <stdio.h> typedef enum {INIT, RUNNING, STOPPED} State; int main() { State s = INIT; switch(s) { case INIT: printf("Init state\n"); s = RUNNING; break; case RUNNING: printf("Running state\n"); break; case STOPPED: printf("Stopped state\n"); break; } return 0; }
Check each line carefully for missing punctuation.
The line s = RUNNING is missing a semicolon at the end, causing a syntax error.
Given the following snippet, which option will cause a compilation error?
typedef enum {S1, S2, S3} State;
State current = S1;
switch(current) {
case S1:
// do something
break;
case S2:
// do something else
break;
case S3:
// final state
break;
}Consider the enum values and what assignments are valid.
Assigning current = 5; is invalid because 5 is not a valid value of the enum State. This causes a compilation warning or error depending on compiler strictness.
Consider this protocol state machine code. How many states will be visited (printed) before the program ends?
#include <stdio.h> typedef enum {START, SEND, RECEIVE, END} State; int main() { State s = START; int count = 0; while(s != END) { switch(s) { case START: printf("START\n"); s = SEND; count++; break; case SEND: printf("SEND\n"); s = RECEIVE; count++; break; case RECEIVE: printf("RECEIVE\n"); s = END; count++; break; default: break; } } printf("States visited: %d\n", count); return 0; }
Count how many times the loop prints and increments count before reaching END.
The loop visits START, SEND, and RECEIVE states, printing each and incrementing count. Then it reaches END and stops. So 3 states visited.