C Basics · beginner · ~8 min

switch / case

Dispatch on integer values cleanly.

Lesson

switch selects one of many branches by integer value. Each case ends with break. Without break, control "falls through" to the next case — sometimes useful, often a bug. Modern compilers warn with -Wimplicit-fallthrough.

switch works only on integral types (including char and enum), not strings.

Code examples

switch (cmd) {
case 'q': quit(); break;
case 'h':
case '?': show_help(); break;       // intentional fall-through
default:  printf("unknown\n");
}

Common mistakes

  • Forgetting break and falling through unintentionally.
  • Declaring a variable inside a case without braces — variables declared in one case can leak into others if they share a scope.