switch, case, and fall-through
beginner10 min readLesson 16 of 148
Multi-way branching on one value: case labels, break, default, and when switch beats if.
The shape
switch (choice) {
case 1:
printf("deposit\n");
break;
case 2:
printf("withdraw\n");
break;
default:
printf("unknown\n");
break;
}
- The controlling value must be an integer type (int, char, enum โ module 15).
caselabels are entry points, not sections: withoutbreak, execution falls through into the next case. Occasionally useful (grouping cases), usually a bug.defaultruns when nothing matched โ handle it explicitly.
switch vs if
Use switch when one integral value selects among fixed options (menus,
state codes). Use if for ranges (x > 100) and mixed conditions.