: 1
Task One!
**** Menu ****
(1) Choice one.
(2) Choice two.
(3) Choice three.
(4) Redisplay menu.
(5) Quit.
: 3
Task Three!
**** Menu ****
(1) Choice one.
(2) Choice two.
(3) Choice three.
(4) Redisplay menu.
(5) Quit.
: 5
This program brings together a number of concepts from today and previous
days. It also shows a common use of the switchstatement.
The forever loop begins on line 15. The menu()function is called, which prints the menu
to the screen and returns the user’s selection. The switchstatement, which begins on line
18 and ends on line 38, switches on the user’s choice.
If the user enters 1, execution jumps to the case (1):statement on line 20. Line 21
switches execution to the DoTaskOne()function, which prints a message and returns. On
its return, execution resumes on line 22, where the breakends the switchstatement, and
execution falls through to line 39. On line 40, the variable exitis evaluated to see
whether it is true. If it evaluates true, the breakon line 41 is executed and the for(;;)
loop ends; but if it evaluates false, execution resumes at the top of the loop on line 15.
Note that the continuestatement on line 30 is redundant. If it were left out and the
breakstatement were encountered, the switch would end,exitwould evaluate false, the
loop would reiterate, and the menu would be reprinted. The continuedoes, however,
bypass the test of exit.
204 Day 7
ANALYSIS
DOcarefully document all intentional
fall-through cases.
DOput a default case in switchstate-
ments, if only to detect seemingly impos-
sible situations.
DON’Tuse complex if...elsestate-
ments if a clearer switchstatement will
work.
DON’Tforget breakat the end of each
case unless you want to fall through.
DO DON’T