Namespaces
Variants
Actions

intro/control/switch

From cppreference.com
< intro/control
Revision as of 04:51, 22 September 2013 by Roadrunner (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

The switch statement

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.

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.