C — Switch statements and case labels
A C switch dispatches on an integer or enumeration value. Adjacent case labels can share one action, and default handles unrecognized values.
A simple example
Match one case
- Start with Value 2
- Do this Match case 2
- Result two
#include <stdio.h>
int main(void) {
int n = 2;
switch (n) {
case 2: puts("two"); break;
default: puts("other");
}
}
two
Route several event states to one action
Map queued and retry to the same pending action. A sent event is complete, and an unrecognized state is sent for review. The function returns from each selected case, so execution cannot fall into another action. Here enum names give integer event codes readable meanings.
A parcel dashboard receives status updates. A queued parcel and a parcel awaiting retry both belong in the pending tray. Mark a sent parcel done and send unfamiliar statuses for review.
Run the example
Use a C17 compiler. Run these commands from the directory containing the example. Use a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson
#include <stdio.h>
enum event { QUEUED, RETRY, SENT, UNKNOWN };
static const char *route(enum event state) {
switch (state) {
case QUEUED:
case RETRY: return "pending";
case SENT: return "done";
default: return "review";
}
}
int main(void) {
enum event events[] = {QUEUED, RETRY, SENT, UNKNOWN};
for (int i = 0; i < 4; ++i) puts(route(events[i]));
return 0;
}
pending pending done review
Both pending states share one result. The other branches distinguish a known completion from a new or misspelled status.
Try it yourself
What should an unrecognized state such as paused produce?
Check your answer
It produces review. Add an explicit case when the application defines how to handle that state.