Switch

Switch in C++: An / chain is a security guard asking every question in turn: "Are you A? No? Are you B? No? Are you C?" A is a pigeonhole rack in a post room —…

The Analogy: The Pigeonhole Sorting Rack

An if / else if chain is a security guard asking every question in turn: "Are you A? No? Are you B? No? Are you C?" A switch is a pigeonhole rack in a post room — the sorter glances at the label and puts the letter straight into the right slot, without walking past the others.

That is close to what the compiler actually does. For a dense set of integer cases it can build a jump table: compute an offset from the value and jump directly to the right code, in constant time no matter how many cases there are. The cost is that a switch only works on values it can index by — integers, characters and enums — never strings or ranges.


Syntax or Core Structure

#include <iostream>

int main() {
    int day{3};

    switch (day) {
        case 1:
            std::cout << "Monday\n";
            break;                        // stop here -- do NOT continue
        case 2:
            std::cout << "Tuesday\n";
            break;
        case 3:
            std::cout << "Wednesday\n";   // this runs
            break;
        case 6:
        case 7:                           // deliberate grouping: both share one body
            std::cout << "Weekend\n";
            break;
        default:
            std::cout << "Not a valid day\n";
            break;
    }

    char grade{'B'};
    switch (grade) {
        case 'A': std::cout << "Excellent\n"; break;
        case 'B': std::cout << "Good\n";      break;
        case 'C': std::cout << "Adequate\n";  break;
        default:  std::cout << "Unknown\n";   break;
    }

    return 0;
}

Each case label must be a compile-time constant — a literal, a const int, a constexpr, or an enum value. A variable is not allowed, and neither is a range or a condition.


Technical Depth: Fallthrough, Scope and Enums

Fallthrough is the default, and it is dangerous

int day{1};
switch (day) {
    case 1:
        std::cout << "Monday\n";     // runs
    case 2:
        std::cout << "Tuesday\n";    // ALSO runs -- no break above
    case 3:
        std::cout << "Wednesday\n";  // and this
}
// Output: Monday Tuesday Wednesday

A case label is a jump target, not a block. Execution enters at the matching label and then keeps running downwards until it hits break, return, or the closing brace. Forgetting one break is the classic switch bug.

When you want fallthrough, say so out loud (C++17):

switch (level) {
    case 3:
        grantAdmin();
        [[fallthrough]];          // intentional -- silences the warning
    case 2:
        grantWrite();
        [[fallthrough]];
    case 1:
        grantRead();
        break;
}

Level 3 gets all three permissions, level 2 gets two, level 1 gets one. Without the attribute, -Wimplicit-fallthrough warns on every one — which is exactly the warning you want turned on.

The whole switch is one scope

switch (x) {
    case 1:
        int y = 5;              // ERROR: jump to case 2 would skip this initialisation
        break;
    case 2:
        std::cout << y;         // y is in scope but never initialised!
        break;
}

// Fix: give the case its own block
switch (x) {
    case 1: {
        int y = 5;
        std::cout << y;
        break;
    }
    case 2:
        break;
}

All the cases share a single scope, so a declaration in one is visible in the others. The compiler rejects the first version because jumping to case 2 would bypass y's initialiser. Wrap any case that declares variables in its own braces.

default and enums

enum class Status { Pending, Active, Suspended, Closed };

std::string describe(Status s) {
    switch (s) {
        case Status::Pending:   return "Waiting for approval";
        case Status::Active:    return "In good standing";
        case Status::Suspended: return "Temporarily blocked";
        case Status::Closed:    return "Permanently closed";
    }
    return "Unknown";     // unreachable, but keeps the compiler happy
}

This is where switch truly earns its place. Omit default for an enum and -Wswitch will warn the day someone adds Status::Archived and forgets to handle it — the compiler becomes your checklist. Add a default and you lose that warning forever. Note that return inside a case makes break unnecessary.

Switch versus if-else

switchif / else if
Testsequality against constantsany boolean expression
Value typesintegers, chars, enumsanything
Rangesnoyes
Stringsnoyes
Speed with many casesoften constant timelinear scan
Missing-case warningyes, for enumsno

Use switch for a fixed set of discrete values, especially enums. Use if for ranges, strings, floating point, and anything involving more than one variable.


Real World Example: A Menu-Driven Calculator

#include <iostream>
#include <limits>

enum class Op { Add = '+', Sub = '-', Mul = '*', Div = '/' };

int main() {
    bool running{true};

    while (running) {
        std::cout << "\n[+ - * /] operation, or q to quit: ";
        char choice{};
        std::cin >> choice;

        if (choice == 'q' || choice == 'Q') {
            running = false;
            continue;
        }

        // Validate before asking for numbers
        switch (choice) {
            case '+': case '-': case '*': case '/':
                break;                                  // acceptable, carry on
            default:
                std::cout << "Unknown operation.\n";
                continue;                               // back to the top
        }

        double a{}, b{};
        std::cout << "Two numbers: ";
        if (!(std::cin >> a >> b)) {
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            std::cout << "Those were not numbers.\n";
            continue;
        }

        switch (choice) {
            case '+':
                std::cout << "= " << a + b << "\n";
                break;
            case '-':
                std::cout << "= " << a - b << "\n";
                break;
            case '*':
                std::cout << "= " << a * b << "\n";
                break;
            case '/': {                                  // own block: declares a variable
                if (b == 0.0) {
                    std::cout << "Cannot divide by zero.\n";
                } else {
                    const double result = a / b;
                    std::cout << "= " << result << "\n";
                }
                break;
            }
        }
    }

    std::cout << "Goodbye.\n";
    return 0;
}

Two switch statements do two different jobs here. The first validates the choice using grouped case labels — four labels sharing one empty body is the idiomatic "is it one of these?" test. The second dispatches the actual work. The '/' case gets its own braces because it declares result; without them the compiler would reject the initialisation. continue restarts the loop, which is cleaner than nesting the rest of the body inside an else.


Common Mistakes

  • Forgetting break. Execution falls into the next case and does extra work. Turn on -Wimplicit-fallthrough.
  • Switching on a std::string. It does not compile. Use if/else if, or map strings to an enum first.
  • Using a variable as a case label. Labels must be compile-time constants.
  • Declaring a variable in a case without braces. Either a compile error or an uninitialised variable visible in later cases.
  • Adding default to an enum switch and losing the compiler's missing-case warning.
  • Expecting ranges: case 1...5: is a GCC extension, not standard C++.
  • Switching on a double. Not allowed — floating point cannot be a case label.
  • Assuming default must come last. It can appear anywhere, though last is conventional and clearer.

Best Practices

  1. End every case with break or return, and mark deliberate fallthrough with [[fallthrough]].
  2. Prefer enum class over bare integers for the switched value — it is self-documenting and type-safe.
  3. Omit default when switching on an enum so the compiler warns about unhandled values; keep it when the input could be arbitrary, such as a character from a user.
  4. Give each case that declares variables its own braces.
  5. Group related labels (case 6: case 7:) instead of duplicating a body.
  6. Keep case bodies short. If one grows past a few lines, call a named function from it.

Practice Exercises

  1. Day classifier: Read a number 1–7 and use a switch with grouped labels to print "Weekday" or "Weekend", with default handling anything else.
  2. Vowel counter: Read a line and count vowels using a switch on each character, with grouped labels for both cases of each vowel. Compare the code length with an if-based version.
  3. Enum state machine: Define enum class TrafficLight { Red, Amber, Green }; and write TrafficLight next(TrafficLight) using a switch with no default. Add a fourth value to the enum and confirm the compiler warns you.