📄 ch07.htm
字号:
<TT>26: }</TT></FONT>
<FONT COLOR="#0066FF">
Output: Enter a number between 1 and 5: 3
Excellent!
Masterful!
Incredible!
Enter a number between 1 and 5: 8
Too large!
</FONT></PRE>
<P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>The user is prompted for
a number. That number is given to the <TT>switch</TT> statement. If the number is
0, the <TT>case</TT> statement on line 13 matches, the message <TT>Too small, sorry!</TT>
is printed, and the <TT>break</TT> statement ends the switch. If the value is <TT>5</TT>,
execution switches to line 15 where a message is printed, and then falls through
to line 16, another message is printed, and so forth until hitting the <TT>break</TT>
on line 20.<BR>
The net effect of these statements is that for a number between 1 and 5, that many
messages are printed. If the value of number is not 0-5, it is assumed to be too
large, and the <TT>default</TT> statement is invoked on line 21.
<H3 ALIGN="CENTER"><A NAME="Heading57"></A><FONT COLOR="#000077">The switch Statement</FONT></H3>
<P>The syntax for the <TT>switch</TT> statement is as follows:</P>
<PRE><FONT COLOR="#0066FF">switch (expression)
{
case valueOne: statement;
case valueTwo: statement;
....
case valueN: statement
default: statement;
}
</FONT></PRE>
<P>The <TT>switch</TT> statement allows for branching on multiple values of expression.
The expression is evaluated, and if it matches any of the <TT>case</TT> values, execution
jumps to that line. Execution continues until either the end of the <TT>switch</TT>
statement or a <TT>break</TT> statement is encountered. If expression does not match
any of the <TT>case</TT> statements, and if there is a <TT>default</TT> statement,
execution switches to the <TT>default</TT> statement, otherwise the <TT>switch</TT>
statement ends. Example 1</P>
<PRE><FONT COLOR="#0066FF">switch (choice)
{
case 0:
cout << "Zero!" << endl;
break
case 1:
cout << "One!" << endl;
break;
case 2:
cout << "Two!" << endl;
default:
cout << "Default!" << endl;
}
</FONT></PRE>
<P>Example 2</P>
<PRE><FONT COLOR="#0066FF">switch (choice)
{
choice 0:
choice 1:
choice 2:
cout << "Less than 3!";
break;
choice 3:
cout << "Equals 3!";
break;
default:
cout << "greater than 3!";
}
</FONT></PRE>
<H4 ALIGN="CENTER"><A NAME="Heading58"></A><FONT COLOR="#000077">Using a switch Statement
with a Menu</FONT></H4>
<P>Listing 7.17 returns to the <TT>for(;;)</TT> loop discussed earlier. These loops
are also called forever loops, as they will loop forever if a <TT>break</TT> is not
encountered. The forever loop is used to put up a menu, solicit a choice from the
user, act on the choice, and then return to the menu. This will continue until the
user chooses to exit.
<BLOCKQUOTE>
<P>
<HR>
<FONT COLOR="#000077"><B>NOTE:</B></FONT><B> </B>Some programmers like to write
<HR>
</BLOCKQUOTE>
<PRE><FONT COLOR="#0066FF">#define EVER ;;
for (EVER)
{
// statements...
}
</FONT></PRE>
<P>Using <TT>#define</TT> is covered on Day 17, "The Preprocessor."
<DL>
<DD>
<HR>
<FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>A <I>forever loop</I> is a loop
that does not have an exit condition. In order to exit the loop, a <TT>break</TT>
statement must be used. Forever loops are also known as eternal loops.
<HR>
</DL>
<P><A NAME="Heading59"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 7.17. Demonstrating
a forever loop.</B></FONT></P>
<PRE><FONT COLOR="#0066FF">1: //Listing 7.17
2: //Using a forever loop to manage
3: //user interaction
4: #include <iostream.h>
5:
6: // types & defines
7: enum BOOL { FALSE, TRUE };
8: typedef unsigned short int USHORT;
9:
10: // prototypes
11: USHORT menu();
12: void DoTaskOne();
13: void DoTaskMany(USHORT);
14:
15: int main()
16: {
17:
18: BOOL exit = FALSE;
19: for (;;)
20: {
21: USHORT choice = menu();
22: switch(choice)
23: {
24: case (1):
25: DoTaskOne();
26: break;
27: case (2):
28: DoTaskMany(2);
29: break;
30: case (3):
31: DoTaskMany(3);
32: break;
33: case (4):
34: continue; // redundant!
35: break;
36: case (5):
37: exit=TRUE;
38: break;
39: default:
40: cout << "Please select again!\n";
41: break;
42: } // end switch
43:
44: if (exit)
45: break;
46: } // end forever
47: return 0;
48: } // end main()
49:
50: USHORT menu()
51: {
52: USHORT choice;
53:
54: cout << " **** Menu ****\n\n";
55: cout << "(1) Choice one.\n";
56: cout << "(2) Choice two.\n";
57: cout << "(3) Choice three.\n";
58: cout << "(4) Redisplay menu.\n";
59: cout << "(5) Quit.\n\n";
60: cout << ": ";
61: cin >> choice;
62: return choice;
63: }
64:
65: void DoTaskOne()
66: {
67: cout << "Task One!\n";
68: }
69:
70: void DoTaskMany(USHORT which)
71: {
72: if (which == 2)
73: cout << "Task Two!\n";
74: else
75: cout << "Task Three!\n";
<TT>76: }</TT></FONT>
<FONT COLOR="#0066FF">
Output: **** Menu ****
(1) Choice one.
(2) Choice two.
(3) Choice three.
(4) Redisplay menu.
(5) Quit.
: 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
</FONT></PRE>
<P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>This program brings together
a number of concepts from today and previous days. It also shows a common use of
the <TT>switch</TT> statement. On line 7, an enumeration, <TT>BOOL</TT>, is created,
with two possible values: <TT>FALSE</TT>, which equals <TT>0</TT>, as it should,
and <TT>TRUE</TT>, which equals <TT>1</TT>. On line 8, <TT>typedef</TT> is used to
create an alias, <TT>USHORT</TT>, for <TT>unsigned short int</TT>.<BR>
The forever loop begins on 19. The <TT>menu()</TT> function is called, which prints
the menu to the screen and returns the user's selection. The <TT>switch</TT> statement,
which begins on line 22 and ends on line 42, switches on the user's choice.</P>
<P>If the user enters <TT>1</TT>, execution jumps to the <TT>case 1:</TT> statement
on line 24. Line 25 switches execution to the <TT>DoTaskOne()</TT> function, which
prints a message and returns. On its return, execution resumes on line 26, where
the <TT>break</TT> ends the <TT>switch</TT> statement, and execution falls through
to line 43. On line 44, the variable <TT>exit</TT> is evaluated. If it evaluates
<TT>true</TT>, the break on line 45 will be executed and the <TT>for(;;)</TT> loop
will end, but if it evaluates <TT>false</TT>, execution resumes at the top of the
loop on line 19.</P>
<P>Note that the <TT>continue</TT> statement on line 34 is redundant. If it were
left out and the <TT>break</TT> statement were encountered, the <TT>switch</TT> would
end, <TT>exit</TT> would evaluate <TT>FALSE</TT>, the loop would reiterate, and the
menu would be reprinted. The <TT>continue</TT> does, however, bypass the test of
<TT>exit</TT>.
<BLOCKQUOTE>
<P>
<HR>
<B>DO</B> use <TT>switch</TT> statements to avoid deeply nested <TT>if</TT> statements.
<B>DON'T</B> forget <TT>break</TT> at the end of each <TT>case</TT> unless you wish
to fall through.<B> DO </B>carefully document all intentional fall-through <TT>cases</TT>.
<B>DO </B>put a default <TT>case</TT> in <TT>switch</TT> statements, if only to detect
seemingly impossible situations.
<HR>
</BLOCKQUOTE>
<H3 ALIGN="CENTER"><A NAME="Heading61"></A><FONT COLOR="#000077">Summary</FONT></H3>
<P>There are different ways to cause a C++ program to loop. <TT>While</TT> loops
check a condition, and if it is true, execute the statements in the body of the loop.
<TT>do...while</TT> loops execute the body of the loop and then test the condition.
<TT>for</TT> loops initialize a value, then test an expression. If an expression
is true, the final statement in the <TT>for</TT> header is executed, as is the body
of the loop. Each subsequent time through the loop the expression is tested again.</P>
<P>The <TT>goto</TT> statement is generally avoided, as it causes an unconditional
jump to a seemingly arbitrary location in the code, and thus makes source code difficult
to understand and maintain. <TT>continue</TT> causes <TT>while</TT>, <TT>do...while</TT>,
and <TT>for</TT> loops to start over, and <TT>break</TT> causes <TT>while</TT>, <TT>do...while</TT>,
<TT>for</TT>, and <TT>switch</TT> statements to end.
<H3 ALIGN="CENTER"><A NAME="Heading62"></A><FONT COLOR="#000077">Q&A</FONT></H3>
<DL>
<DD><B>Q. How do you choose between if/else and switch?<BR>
</B><BR>
<B>A.</B> If there are more than just one or two <TT>else</TT> clauses, and all are
testing the same value, consider using a <TT>switch</TT> statement.<BR>
<BR>
<B>Q. How do you choose between while and do...while?<BR>
</B><BR>
<B>A.</B> If the body of the loop should always execute at least once, consider a
<TT>do...while</TT> loop; otherwise, try to use the <TT>while</TT> loop.<BR>
<BR>
<B>Q. How do you choose between while and for?<BR>
</B><BR>
<B>A</B> If you are initializing a counting variable, testing that variable, and
incrementing it each time through the loop, consider the <TT>for</TT> loop. If your
variable is already initialized and is not incremented on each loop, a <TT>while</TT>
loop may be the better choice.<BR>
<BR>
<B>Q. How do you choose between recursion and iteration?<BR>
</B><BR>
<B>A</B>. Some problems cry out for recursion, but most problems will yield to iteration
as well. Put recursion in your back pocket; it may come in handy someday.<BR>
<B><BR>
Q. Is it better to use while (1) or for (;;)?<BR>
</B><BR>
<B>A.</B> There is no significant difference.
</DL>
<H3 ALIGN="CENTER"><A NAME="Heading63"></A><FONT COLOR="#000077">Workshop</FONT></H3>
<P>The Workshop provides quiz questions to help you solidify your understanding of
the material covered, as well as exercises to provide you with experience in using
what you've learned. Try to answer the quiz and exercise questions before checking
the answers in
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -