Skip to main content

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).
  • case labels are entry points, not sections: without break, execution falls through into the next case. Occasionally useful (grouping cases), usually a bug.
  • default runs 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

Menu Machineswitch dispatch with default handling โ€” the graded skeleton of every console menu.2 challenges ยท ยท ~12 min