`switch` — C++ Keyword

`switch` — C++ Keyword

The switch keyword in C++: selects among multiple execution paths based on an integral value.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

switch

Selects among multiple execution paths based on the value of an integral or enumeration expression.

Syntax

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

switch (init-statement; expression) { ... }  // C++17 init-statement form

Example

#include <print>

int main() {
    int day = 3;

    switch (day) {
        case 1: std::println("Monday");    break;
        case 2: std::println("Tuesday");   break;
        case 3: std::println("Wednesday"); break;   // executed
        case 4: std::println("Thursday");  break;
        case 5: std::println("Friday");    break;
        default: std::println("Weekend");
    }
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}