Many people believe that the default case of a switch statement must be the last statement. This is not
true, the default may be first, last, or anywhere.
Starting with Slide 12 we begin to teach some of the style rules used with switch statements. We first
present a code fragment that doesn’t follow the rules, followed by a corrected fragment. Emphasize that
these rules make your code clearer, easier to maintain and more reliable.
For example, the code on Slide 14 contains a problem. We’ve just added “case 3.” We didn’t have a
break at the end of “case 2” on the previous page. Normally this would be OK as it was the last case in
the statement. But we’ve added “case 3” and caused trouble at “case 2.” In this example, if control is 2
the output is:
Working
Closing down
This is not what the programmer wanted.
Finally we present switch, break, and continue. The break statement works inside of loops and switch
statements. The continue statement works inside loops only.
In our diagram we have continue inside a switch. This works because the switch is inside a loop. The
continue doesn’t care about the switch, it cares about the loop.
If possible, step through the program on Slide 17 to illustrate the paths outlined in the diagram.
Review Questions
9. Why do C++ programs count to five by saying “0, 1, 2, 3, 4?” Why should you learn to count
that way?
C++ uses “zero based” counting. For example, an array with 5 elements uses the numbers
0, 1, 2, 3, 4 to index the array.
10. Write a for statement to zero the following array:
int data[10];
(Did you call your index “i”? If so go back and give it a real name. )
for (data_index = 0; data_index < 10; ++data_index)
data[data_index] = 0;
Page 25
11. Why do we end each case with break or // Fall through?
Without the // Fall through we can’t tell whether or not the programmer who
wrote his code intended for the program to fall through to the next case or forgot to put in
the break. The // Fall through statement tells everyone, “Yes, you are supposed to
fall through to the next case here.”
12. Why do we always put a break at the end of each switch?
Because some day we might add another case onto the end of the switch and forget to go
back and put in the break that was missing. Also, if we always put in the break , we don’t
have to think about whether or not we can safely omit it.
13. What will continue do inside of a while?
It causes the program to jump to the top of the loop.
Practical C++ Programming by manish baranwal
Start from the beginning
