< previous page page_462 next page >

Page 462
The data type of ConstantExpression is coerced, if necessary, to match the type of the switch expression.
In our opening example that tests the value of letter, the following are case labels:
case X :
case L :
case M :
case S :
As the example shows, a single statement may be preceded by more than one case label. Each case constant may appear only once in a given Switch statement. If a value appears more than once, a syntax error results. Also, there can be only one default label in a Switch statement.
The flow of control through a Switch statement goes like this. First, the switch expression is evaluated. If the value matches one of the constants in a case label, control branches to the statement following that case label. From there, control proceeds sequentially until either a break statement or the end of the Switch statement is encountered. If the value of the switch expression doesn't match any case constant, then one of two things happens. If there is a default label, control branches to the statement following that label. If there is no default label, all statements within the Switch are skipped and control simply proceeds to the statement following the entire Switch statement.
The following Switch statement prints an appropriate comment based on a student's grade (grade is of type char):
switch (grade)
{
    case A :
    case B : cout << Good Work;
                           break;
    case C : cout << Average Work;
                           break;
    case D :
    case F : cout << Poor Work;
                           numberInTrouble++;
                           break;               // Unnecessary, but a good habit
}
Notice that the final break statement is unnecessary. But programmers often include it anyway. One reason is that it's easier to insert another case label at the end if there is already a break statement present.
If grade does not contain one of the specified characters, none of the statements within the Switch is executed. Unless a precondition of the

 
< previous page page_462 next page >