Switch Case

Switch Case Statements in C++

A guide to switch case statements in C++: syntax, break and fall-through, the default label, what you can switch on and when if else works better.

On this page
  1. What a switch statement does
  2. Basic syntax
  3. A small working example
  4. How break and fall-through work
  5. The default label
  6. What you can switch on
  7. Switching over an enum
  8. Declaring variables inside a case
  9. Switch or if else?
  10. Other things to know
  11. Summary

What a switch statement does

A switch statement compares one value with a list of constant labels and runs the code under the label that matches. If no label matches and the statement has a default label, the code under default runs instead. A switch is most useful when one variable can hold a few known values, such as a menu choice, a status code or a day number, and each value needs its own action.

Basic syntax

switch (expression) {
    case constant1:
        // statements
        break;
    case constant2:
        // statements
        break;
    default:
        // statements
        break;
}

The expression is evaluated once. Each case label must be a constant, such as a literal like 2 or 'x', or an enumerator, and no two labels can have the same value. The default label is optional and is usually written last. For a shorter walkthrough of the same form, see how to write a switch case in c.

A small working example

#include <iostream>

int main() {
    int day = 3;

    switch (day) {
        case 1:
            std::cout << "Monday\n";
            break;
        case 2:
            std::cout << "Tuesday\n";
            break;
        case 3:
            std::cout << "Wednesday\n";
            break;
        default:
            std::cout << "Another day\n";
            break;
    }

    return 0;
}

Because day is 3, the program jumps to case 3, prints Wednesday and reaches the break, which leaves the switch. The output is:

Wednesday

How break and fall-through work

A case label is only a place to jump to. From there, execution keeps going through the cases below it until it reaches a break, a return, or the closing brace of the switch. This is called fall-through, and it is one of the most common surprises with switch statements.

int level = 2;

switch (level) {
    case 1:
        std::cout << "Level 1\n";
    case 2:
        std::cout << "Level 2\n";
    case 3:
        std::cout << "Level 3\n";
        break;
}

With level set to 2, this prints Level 2 and then Level 3, because nothing stops the program after the first line. The break is the usual way to stop this. The break statement in c covers how it works in loops and switches alike.

Fall-through is sometimes useful, for example when several values should share one action:

switch (day) {
    case 6:
    case 7:
        std::cout << "Weekend\n";
        break;
    default:
        std::cout << "Weekday\n";
        break;
}

Since C++17, you can mark a fall-through as intentional with [[fallthrough]]; placed just before the next case label. It tells the reader the gap is deliberate and keeps compilers that warn about unmarked fall-through quiet.

switch (level) {
    case 1:
        std::cout << "Level 1\n";
        [[fallthrough]];
    case 2:
        std::cout << "Level 2\n";
        break;
}

The default label

default runs when no case matches. It is worth adding even when you think every value is covered, because an unexpected value would otherwise be ignored without any sign. A default block can print an error message or set a flag, for example.

What you can switch on

The value being switched on must have an integer type, such as int, short or char, or an enumeration type. It cannot be a std::string, and it cannot be a floating-point type such as float or double. Each case label must be a constant integer or enumerator. To switch on a string, compare it with if and else, or map the string to an enum value first.

Switching over an enum

An enum is one of the most common things to switch on, because each enumerator can have its own case:

enum class Light { Red, Yellow, Green };

void announce(Light light) {
    switch (light) {
        case Light::Red:
            std::cout << "Stop\n";
            break;
        case Light::Yellow:
            std::cout << "Slow down\n";
            break;
        case Light::Green:
            std::cout << "Go\n";
            break;
    }
}

If enums are new to you, the enum example in c explains how they are declared. Turning on warnings with -Wall in GCC or Clang usually includes a check that reports a missing enumerator when the switch has no default, which helps when you add a new value later.

Declaring variables inside a case

All the cases share the same block, so a variable declared in one case is in scope for the cases after it. C++ does not allow a jump to a case label that skips past a variable declaration with an initializer, even if the later case never uses that variable. The code will not compile. Wrapping the body of the case in braces limits the variable to that one case:

switch (choice) {
    case 1: {
        int total = 0;
        // ...
        break;
    }
    case 2:
        // ...
        break;
}

Switch or if else?

Use a switch when you are checking one value against several exact constants. Use if and else when:

  • the checks are ranges or combinations, such as score >= 90
  • you need to compare a string or a floating-point number
  • there are only one or two branches

For ranges, the if else statement syntax in c is the better fit:

if (score >= 90) {
    std::cout << "A\n";
} else if (score >= 80) {
    std::cout << "B\n";
} else {
    std::cout << "Below B\n";
}

Compilers often turn a switch into a jump table when the values are close together, so speed is rarely the reason to pick one over the other. For a one-line choice between two values, the conditional operator in c is shorter. A switch reads better once there are several values to handle.

Other things to know

  • Since C++17, the condition can declare a variable, as in switch (int code = 2; code). That variable exists only inside the switch.
  • A break inside a switch that sits in a loop leaves only the switch. The loop keeps running.
  • Standard C++ does not allow ranges in case labels, such as case 1 ... 5:. GCC accepts that as an extension, but code that uses it is not portable.

Summary

A switch picks one case by exact value, runs the code from that label down until a break, and falls back to default when nothing matches. Use it when one value is compared with several exact constants, and use if and else for ranges and for strings.

Keep exploring

Guides from other topics

All topics →

Friend Functions in C++

Learn what a friend function is in C++, how the friend keyword lets a non-member function reach private members, and when to use one, with code examples.