๐ WAYPOINT LESSON
switch, case, and fall-through
โญ beginnerโณ 10 min read๐ Lesson 16 of 225
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.
โก Now practice
Ready to CodeMenu Machineswitch dispatch with default handling โ the graded skeleton of every console menu.
2 challenges ยท ยท ~12 min