switch, case, default Statements

switch( expression )
{
[case constant-expression:]
. . .
[statement]
. . .
[default:
statement]
}

The switch and case keywords evaluate expression and execute any statement associated with constant-expression whose value matches the initial expression.

If there is no match with a constant expression, the statement associated with the default keyword is executed. If the default keyword is not used, control passes to the statement following the switch block.

For related information, see if and break.

Examples

All three statements of the switch body in the following example are executed if c is equal to 'A' since a break statement does not appear before the following case. Execution control is transferred to the first statement (capa++;) and continues in order through the rest of the body. If c is equal to 'a', lettera and total are incremented. Only total is incremented if c is not equal to 'A' or 'a'.

switch( c ) 
{
    case 'A':
        capa++;
    case 'a':
        lettera++;
    default :
        total++;
}

In the following example, a break statement follows each statement of the switch body. The break statement forces an exit from the statement body after one statement is executed. If i is equal to –1, only n is incremented. The break following the statement n++; causes execution control to pass out of the statement body, bypassing the remaining statements. Similarly, if i is equal to 0, only z is incremented; if i is equal to 1, only p is incremented. The final break statement is not strictly necessary, since control passes out of the body at the end of the compound statement, but it is included for consistency.

switch( i ) 
{
    case -1:
        n++;
        break;
    case 0 :
        z++;
        break;
    case 1 :
        p++;
        break;
}