C++ ยท Chapter 16 of 49

C++ Switch

The `switch` statement compares one value against multiple `case` labels, which is often clearer than a long if/else-if chain. Each case should end with `break` to prevent falling through to the next case.

switch only works with integral types (int, char, enum) and constant case labels โ€” it cannot switch on strings or floating-point values directly.

How switch works

The expression in `switch()` is compared to each `case` value; execution jumps to the matching label and continues until a `break` or the end of the switch.

Fall-through and default

Omitting `break` lets execution 'fall through' into the next case โ€” sometimes intentional but often a bug. `default` runs when no case matches.

Example 1 (cpp)
int day = 3;
switch (day) {
    case 1: std::cout << "Mon"; break;
    case 3: std::cout << "Wed"; break;
    default: std::cout << "Other";
}
Output
Wed

day matches case 3, so 'Wed' is printed.

Key points

  • switch compares a value against case labels.
  • break prevents fall-through into the next case.
  • default runs if no case matches.
  • switch works only with integral/enum types.
๐Ÿ’ก Note: Modern C++ compilers can warn on missing break with [[fallthrough]] used to mark intentional fall-through.

๐Ÿ“ Quick Quiz

1. What keyword prevents fall-through in a switch?

2. Which case runs when nothing matches?

3. switch can be used with: