Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

switch — selection by value

The switch statement transfers control to a case label matching the condition's value, or to an optional default label. Labels do not end a branch: break exits switch, while [[fallthrough]]; marks intentional continuation.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

switch ( condition ) statement
switch ( init-statement condition ) statement
// Typical body:
// { case constant-expression: statements; break; default: statements; }

switch selects an execution starting point using the condition's value. The condition must have an integral or enumeration type, or a class type with a suitable contextual implicit conversion to one of those types; integral promotions then apply where applicable. The expression in a case label must be a converted constant expression of the adjusted condition type, not merely a constant expression that can be converted to that type. For example, case 1.0: is ill-formed when the condition has type int: the implicit conversion from double to int is not permitted in a converted constant expression. The values of the case labels must be distinct after conversion.

If nothing matches, the optional default label is used; without it, the body is skipped. Labels do not stop execution. break terminates the innermost enclosing loop or switch, so inside a nested loop it exits that loop. [[fallthrough]]; marks intentional continuation to the next case or default label of the same switch, without changing control flow.

The optional initialization statement ends with a semicolon: switch (int choice = 2; choice). The variable choice is available in the condition and body. Labels alone do not create separate scopes. Use { ... } around branches with local variables so that jumping to another label does not bypass their required initialization.

The example prints two, then shared, each on its own line. This entry targets C++23; the source is an evolving draft rather than a frozen C++23 edition. The repository compiler flag does not attest the production runtime; the example requires local verification.

Examples

#include <iostream>

int main() {
    switch (int choice = 2; choice) {
        case 1:
            std::cout << "one\n";
            break;
        case 2:
            std::cout << "two\n";
            [[fallthrough]];
        case 3:
            std::cout << "shared\n";
            break;
        default:
            std::cout << "other\n";
            break;
    }
}

Result

two
shared

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources