The switch Statement

The switch statement allows you to branch to various sections of code based on the value of a single variable. This variable must evaluate to a char, int, or long constant.

Each section of code in the switch statement is marked with a case label—the keyword case followed by a constant or constant expression. The value of the switch test expression is compared to the constant in each case label. If a match is found, control transfers to the statement after the matching label and continues until you reach a break statement or the end of the switch statement.

For example:

switch( answer )

{

case 'y': /* First case */

printf( “lowercase y\n” );

break;

case 'n': /* Another case */

printf( “lowercase n\n” );

break;

default: /* Default case */

printf( “not a lowercase y or n\n” );

break;

}

The example tests the value of the variable answer. If answer evaluates to the constant 'y', control transfers to the first case in the switch statement. If it equals 'n', control transfers to the second case.

A case labelled with the default keyword executes when none of the other case constants matches the value of the switch test expression. In the example, the default case executes when answer equals any value other than 'y' or 'n'.

If you omit the break statement at the end of a case, execution falls through to the next case.

If you omit the default case and no matching case is found, nothing in the switch statement executes.

No two case constants in the same switch statement can have the same value.