Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 171 Β· Control Flow

switch Statements

Learn the C++ switch statement - case labels, break and fall-through, [[fallthrough]], switching on enums, switch with an initializer, case scope rules and when to use it.

When a program must choose between many paths based on a single value, an if/else if chain gets repetitive: if (key == 'w') ... else if (key == 'a') ... else if (key == 's') ..., with the same variable tested over and over. The switch statement expresses that choice directly. You give it one value, list the possible cases, and it jumps straight to the matching one.

A switch is more than shorthand. The compiler can check that you've handled every value of an enumeration, and it can often turn a dense switch into a jump table, which finds the right case in one step instead of testing each condition in turn. But switch also has an old, famous trap called fall-through. In this lesson you'll learn the syntax, how break and fall-through work, the [[fallthrough]] attribute, switching on enums, switch with an initializer (C++17), and the scope rule that causes the puzzling "jump to case label" error.

The basic switch

A switch evaluates its expression once, then jumps to the case label with the same value. If no label matches, it jumps to default, or skips the whole switch if there's no default.

C++ A tiny calculator

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Try your own expressions in the Input box. A few rules shape every switch:

  • The expression must be an integer, a char, a bool or an enumeration (or a class that converts to one of those). You can't switch on a std::string, a double or a pointer; the compiler says "switch quantity not an integer".
  • Each case label must be a constant expression: a literal, a constexpr variable or an enumerator. case limit: with an ordinary variable doesn't compile.
  • No two labels may have the same value, and there's at most one default.
  • default can go anywhere, but by convention it's last.

The usual formatting puts case labels at the same indentation as switch (as above) or one level in. Both are common; pick one and be consistent.

break and fall-through

Here's the part that surprises newcomers: a case label is only an entry point. Once execution jumps to a label, it runs statement after statement until it hits a break (or return, continue, throw or the end of the switch). It does not stop at the next case label. Forgetting a break makes execution fall through into the next case:

C++ Missing break: fall-through

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

GCC catches the accident: with -Wextra it warns "this statement may fall through" on the first switch, as you can see above the output. This example leaves the bug in on purpose so you can see both the warning and the wrong result. Accidental fall-through has caused real outages, so treat this warning as an error.

Putting break after the last case (here default) isn't required, but it's a good habit: if someone adds a case below it later, they won't inherit a fall-through bug.

Grouping cases on purpose

Fall-through is useful in one form that never triggers a warning: several labels in a row with no statements between them. They all share the same code.

C++ Several labels, one action

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Each return leaves the function, so no break is needed. Switches that return a value per case are very common and read nicely.

case 1 ... 5: is not standard C++. GCC and Clang accept case ranges as an extension, and you'll see them in Linux kernel code, but MSVC rejects them and -Wpedantic warns. For ranges of values, use an if/else if chain instead.

[[fallthrough]]: saying "I meant it"

Sometimes falling through from one case with code into the next is exactly what you want. C++17's [[fallthrough]]; attribute, placed as the last statement before the next label, documents the intent and silences the warning:

C++ Deliberate fall-through with [[fallthrough]]

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

[[fallthrough]] must be directly followed by a case label; putting it anywhere else is an error. Readers should never have to guess whether a missing break was a mistake.

Switching on enums

Switches and enumerations are natural partners. With a scoped enum class, the case labels are the enumerators, and the compiler can check your work: if a switch on an enum has no default and you forget an enumerator, GCC warns (-Wswitch, part of -Wall).

C++ switch on an enum class

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Delete the case Light::Green: lines and run again: GCC warns "enumeration value 'Green' not handled in switch". That's why many teams leave out default when switching on their own enums. When someone adds Light::Blinking next year, every switch that needs updating shows up as a warning instead of silently doing the default thing.

The final return after the switch is still needed. An enum variable can hold values that aren't named enumerators (for example after static_cast<Light>(7)), and without that line GCC warns that control can reach the end of a non-void function.

switch with an initializer (C++17)

Like if, switch can declare a variable that is visible only inside the statement: switch (init; expression).

C++ switch with initializer

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Integer division by 100 groups HTTP status codes into families (404 / 100 is 4), which is a handy way to switch on a range when the ranges line up with a simple formula.

Scope inside a switch

The whole body of a switch is one block, and the case labels are just positions inside it. That creates a rule that confuses many people. You can't jump past the initialization of a variable that is still in scope at the target. This doesn't compile:

C++
switch (choice) {
case 1:
    int bonus = 10;               // in scope for the rest of the switch body...
    std::println("bonus {}", bonus);
    break;
case 2:                           // error: jump to case label
    std::println("two");          // note: crosses initialization of 'int bonus'
    break;
}

Jumping to case 2 would skip bonus's initialization while bonus is still in scope, so C++ forbids it. The fix is to give the case its own block with braces, so the variable's scope ends before the next label:

C++
switch (choice) {
case 1: {
    int bonus = 10;
    std::println("bonus {}", bonus);
    break;
}
case 2:
    std::println("two");
    break;
}

Get into the habit: if a case needs local variables, wrap it in braces.

switch or if?

Use switch when… Use if/else if when…
you compare one integer, char or enum value conditions involve different variables
against many constant values you test ranges (score >= 90)
you want the compiler to check all enumerators you compare strings or floating point
there are only two or three choices

To "switch on a string", map the strings to an enum or an integer first (for example with a std::map<std::string, Command>), then switch on that. A long if chain comparing strings also works and is perfectly fine for a handful of options.

Performance rarely decides it. Modern compilers turn both forms into similar code when they can, but a switch over dense values (like 0 to 20) reliably becomes a jump table. Choose whichever states your intent most clearly.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. int n = 2; What does this print? switch (n) { case 1: print("a"); case 2: print("b"); case 3: print("c"); break; default: print("d"); }

    Execution jumps to case 2, prints b, falls through into case 3 (no break), prints c, and then break leaves the switch before default.
  2. 2. Which of these can be the controlling expression of a switch?

    switch works on integral types, char, bool and enumerations (including scoped enums). Strings, floating point and pointers are not allowed.
  3. 3. Why does GCC report "jump to case label ... crosses initialization of 'int x'"?

    The switch body is one block. Wrap the case that declares the variable in its own braces so the variable's scope ends before the next label.
  4. 4. What does [[fallthrough]]; do?

    [[fallthrough]] is an attribute that documents intent and suppresses -Wimplicit-fallthrough. It must be immediately followed by a case or default label.
  5. 5. Why do many teams omit default when switching over their own enum class?

    Without default, -Wswitch reports every unhandled enumerator, so adding a new value points you at every switch that needs updating.

Summary

  • switch (value) jumps to the case with a matching constant, or to default; it works on integers, char, bool and enums.
  • Case labels are entry points: without break (or return) execution falls through into the next case. -Wextra warns about it.
  • Stack several labels together to share code; mark deliberate fall-through with [[fallthrough]];.
  • Switch on enum class values without a default to get -Wswitch warnings for unhandled enumerators.
  • switch (init; value) (C++17) scopes a helper variable to the switch.
  • The switch body is one scope: wrap cases that declare variables in braces to avoid "jump to case label".
  • Use switch for one value against many constants; use if for ranges, strings and mixed conditions.

Next: while and do-while Loops, where you'll repeat code until a condition changes.