switch statement

From Cppreference

Jump to: navigation, search

Executes code according to value of an integral argument

Used where one or several out of many branches of code need to be executed according to an integral value.

Contents

[edit] Syntax

switch ( expression ) {
case constant_expression1 :
statement1 (optional)
case constant_expression2 :
statement2 (optional)
... ... ...
case constant_expressionn :
statementn (optional)
default: statementn (optional)

}

[edit] Explanation

expression shall be an expression, convertible to an integer value.

All constant_expressions shall be constant expressions, convertible to an integer value, which is unique withing this switch statement

If the expression evaluates to a value, equal to the value of one of the defined constant_expressioni, the statementi (if present) and all subsequent statements (except default_statement, if present) are executed. If the value of the expression does not match any of the constant_expressions, the default_statement is executed if present.

It is useful to note, that if the execution of subsequent statements is undesirable, the break statement can be used. In that case the execution of the switch statement terminates.

[edit] Keywords

switch, case, default

[edit] Example

The following code shows several usage cases of the switch statement

#include <iostream>
 
int main()
{
    int i = 2;
    switch (i) {
        case 1: std::cout << "1";
        case 2: std::cout << "2";   //execution starts at this case label
        case 3: std::cout << "3";
        case 4:
        case 5: std::cout << "45";
                break;              //execution of subsequent statements is terminated
        case 6: std::cout << "6";
    }
 
    std::cout << '\n';
 
    switch (i) {
        case 4: std::cout << "a";
        default: std::cout << "d"; //there are no applicable constant_expressions 
                                   //therefore default_statement is executed
    }
 
    std::cout << '\n';
 
    switch (i) {
        case 4: std::cout << "a";  //nothing is executed
    }
    }

Output:

2345
d