< previous page page_463 next page >

Page 463
Switch statement is that grade is definitely one of A, B, C, D, or F, it would be wise to include a default label to account for an invalid grade:
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;
    default  : cout << grade <<  is not a legal letter grade.;
               break;
}
A Switch statement with a break statement after each case alternative behaves exactly like an If-Then-Else-If control structure. For example, our Switch statement is equivalent to the following code:
if (grade == A || grade == B)
    cout << Good Work;
else if (grade == C)
    cout << Average Work;
else if (grade == D || grade == F)
{
    cout << Poor Work;
    numberInTrouble++;
}
else
    cout << grade <<  is not a legal letter grade.;
Is either of these two versions better than the other? There is no absolute answer to this question. For this particular example, our opinion is that the Switch statement is easier to understand because of its two-dimensional, table-like form. But some may find the If-Then-Else-If version easier to read. When implementing a multi-way branching structure, our advice is to write down both a Switch and an If-Then-Else-If and then compare them for readability. Keep in mind that C++ provides the Switch statement as a matter of convenience. Don't feel obligated to use a Switch statement for every multiway branch.
Finally, we said we would look at what happens if you omit the break statements inside a Switch statement. Let's rewrite our letter grade example without the break statements:

 
< previous page page_463 next page >