📄 ch07.htm
字号:
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; breakcase 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 Statementwith a Menu</FONT></H4><P>Listing 7.17 returns to the <TT>for(;;)</TT> loop discussed earlier. These loopsare also called forever loops, as they will loop forever if a <TT>break</TT> is notencountered. The forever loop is used to put up a menu, solicit a choice from theuser, act on the choice, and then return to the menu. This will continue until theuser 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. Demonstratinga forever loop.</B></FONT></P><PRE><FONT COLOR="#0066FF">1: //Listing 7.172: //Using a forever loop to manage3: //user interaction4: #include <iostream.h>5:6: // types & defines7: enum BOOL { FALSE, TRUE };8: typedef unsigned short int USHORT;9:10: // prototypes11: 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 switch43:44: if (exit)45: break;46: } // end forever47: 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: else75: 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.: 1Task One! **** Menu ****(1) Choice one.(2) Choice two.(3) Choice three.(4) Redisplay menu.(5) Quit.: 3Task 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 togethera number of concepts from today and previous days. It also shows a common use ofthe <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 tocreate 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 printsthe 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> statementon line 24. Line 25 switches execution to the <TT>DoTaskOne()</TT> function, whichprints a message and returns. On its return, execution resumes on line 26, wherethe <TT>break</TT> ends the <TT>switch</TT> statement, and execution falls throughto 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> loopwill end, but if it evaluates <TT>false</TT>, execution resumes at the top of theloop on line 19.</P><P>Note that the <TT>continue</TT> statement on line 34 is redundant. If it wereleft out and the <TT>break</TT> statement were encountered, the <TT>switch</TT> wouldend, <TT>exit</TT> would evaluate <TT>FALSE</TT>, the loop would reiterate, and themenu 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> loopscheck 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 expressionis true, the final statement in the <TT>for</TT> header is executed, as is the bodyof 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 unconditionaljump to a seemingly arbitrary location in the code, and thus makes source code difficultto 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 ofthe material covered, as well as exercises to provide you with experience in usingwhat you've learned. Try to answer the quiz and exercise questions before checkingthe answers in Appendix D, and make sure you understand the answers before continuingto the next chapter.<H4 ALIGN="CENTER"><A NAME="Heading64"></A><FONT COLOR="#000077">Quiz</FONT></H4><DL> <DD><B>1.</B> How do I initialize more than one variable in a <TT>for</TT> loop?<BR> <BR> <B>2.</B> Why is <TT>goto</TT> avoided?<BR> <BR> <B>3.</B> Is it possible to write a <TT>for</TT> loop with a body that is never executed?<BR> <BR> <B>4.</B> Is it possible to nest <TT>while</TT> loops within <TT>for</TT> loops?<BR> <BR> <B>5</B>. Is it possible to create a loop that never ends? Give an example.<BR> <BR> <B>6.</B> What happens if you create a loop that never ends?</DL><H4 ALIGN="CENTER"><A NAME="Heading65"></A><FONT COLOR="#000077">Exercises</FONT></H4><DL> <DD><B>1.</B> What is the value of <TT>x</TT> when the <TT>for</TT> loop completes?</DL><PRE><FONT COLOR="#0066FF">for (int x = 0; x < 100; x++)</FONT></PRE><DL> <DD><B>2.</B> Write a nested <TT>for</TT> loop that prints a 10x10 pattern of <TT>0</TT>s.<BR> <BR> <B>3.</B> Write a <TT>for</TT> statement to count from 100 to 200 by 2s.<BR> <BR> <B>4.</B> Write a <TT>while</TT> loop to count from 100 to 200 by 2s.<BR> <BR> <B>5.</B> Write a <TT>do...while</TT> loop to count from 100 to 200 by 2s.<BR> <BR> <B>6</B>. BUG BUSTERS: What is wrong with this code?</DL><PRE><FONT COLOR="#0066FF">int counter = 0while (counter < 10){ cout << "counter: " << counter;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -