Namespaces
Variants
Views
Actions

The switch statement

From cppreference.com


The switch statement takes an integer and executes the corresponding set of statements.

switch(/*Integer value*/)
{
    case 0: //commands
            break;
    case 1: //commands
            break;
    ...
}

The switch statement takes an integer value or a command returning an integer value as a parameter. It then jumps to the case block marked with this number and executes from there on. For instance, if you pass one to the switch statement specified above, it will jump to this line:

case 1: //commands

A little example:

switch((2*6) / 4 - 2)
{
    case 0: std::cout << 0;
            break;
    case 1: std::cout << 1;
            break;
    case 2: std::cout << 2;
            break;
}

Will print 1 to the standart output: (2*6) / 4 - 2 equals 1, therefore the case 1: block is executed.

[edit] The break statement

Note the break; command after each block has executed in the examples above. This keyword is necessary because switch only jumps to the correct case line, but does not return. Therefore, if you removed the break commands in the given example, switch would jump to case 1: and go on to case 2: and every other following case block unless it reaches either the closing bracket for the entire switch block or it encounters a break;, forcing it to leave the switch block.

This usually is not what you want, so make sure you don't forget your breaks.

[edit] The default statement

A typical unsigned int variable can take values up to over 4 billion, and you certainly won't be able to cover 4 billion different possibilities with specific case statements. That's why there is the default statement, which is somehow similiar to the else statement: If there is no case statement covering the specified number available within the current switch block, the default block will be called:

switch(...)
{
    case 0: ...
    default: ...
}

If a number not equal to zero is passed, the default block will be called.