📄 ch04.htm
字号:
<PRE><FONT COLOR="#0066FF">if (expression) statement;next statement;</FONT></PRE><P>If the expression is evaluated as <TT>TRUE</TT>, the statement is executed andthe program continues with the next statement. If the expression is not true, thestatement is ignored and the program jumps to the next statement. Remember that thestatement can be a single statement ending with a semicolon or a block enclosed inbraces. Form 2</P><PRE><FONT COLOR="#0066FF">if (expression) statement1;else statement2;next statement;</FONT></PRE><P>If the expression evaluates <TT>TRUE</TT>, <TT>statement1</TT> is executed; otherwise,<TT>statement2</TT> is executed. Afterwards, the program continues with the nextstatement. Example 1</P><PRE><FONT COLOR="#0066FF">Exampleif (SomeValue < 10) cout << "SomeValue is less than 10");else cout << "SomeValue is not less than 10!");cout << "Done." << endl;</FONT></PRE><CENTER><H4><A NAME="Heading32"></A><FONT COLOR="#000077">Advanced if Statements</FONT></H4></CENTER><P>It is worth noting that any statement can be used in an <TT>if</TT> or <TT>else</TT>clause, even another <TT>if</TT> or <TT>else</TT> statement. Thus, you might seecomplex <TT>if</TT> statements in the following form:</P><PRE><FONT COLOR="#0066FF">if (expression1){ if (expression2) statement1; else { if (expression3) statement2; else statement3; }}else statement4;</FONT></PRE><P>This cumbersome <TT>if</TT> statement says, "If expression1 is true and expression2is true, execute statement1. If expression1 is true but expression2 is not true,then if expression3 is true execute statement2. If expression1 is true but expression2and expression3 are false, execute statement3. Finally, if expression1 is not true,execute statement4." As you can see, complex <TT>if</TT> statements can be confusing!</P><P>Listing 4.6 gives an example of such a complex <TT>if</TT> statement.</P><P><A NAME="Heading33"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 4.6. A complex,nested if statement.</B></FONT><FONT COLOR="#0066FF"></FONT><PRE><FONT COLOR="#0066FF">1: // Listing 4.5 - a complex nested2: // if statement3: #include <iostream.h>4: int main()5: {6: // Ask for two numbers7: // Assign the numbers to bigNumber and littleNumber8: // If bigNumber is bigger than littleNumber,9: // see if they are evenly divisible10: // If they are, see if they are the same number11:12: int firstNumber, secondNumber;13: cout << "Enter two numbers.\nFirst: ";14: cin >> firstNumber;15: cout << "\nSecond: ";16: cin >> secondNumber;17: cout << "\n\n";18:19: if (firstNumber >= secondNumber)20: {21: if ( (firstNumber % secondNumber) == 0) // evenly divisible?22: {23: if (firstNumber == secondNumber)24: cout << "They are the same!\n";25: else26: cout << "They are evenly divisible!\n";27: }28: else29: cout << "They are not evenly divisible!\n";30: }31: else32: cout << "Hey! The second one is larger!\n";33: return 0;<TT>34: }</TT></FONT><FONT COLOR="#0066FF">Output: Enter two numbers.First: 10Second: 2They are evenly divisible!</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>Two numbers are promptedfor one at a time, and then compared. The first <TT>if</TT> statement, on line 19,checks to ensure that the first number is greater than or equal to the second. Ifnot, the <TT>else</TT> clause on line 31 is executed.<BR>If the first <TT>if</TT> is true, the block of code beginning on line 20 is executed,and the second <TT>if</TT> statement is tested, on line 21. This checks to see whetherthe first number modulo the second number yields no remainder. If so, the numbersare either evenly divisible or equal. The <TT>if</TT> statement on line 23 checksfor equality and displays the appropriate message either way.</P><P>If the <TT>if</TT> statement on line 21 fails, the <TT>else</TT> statement online 28 is executed.<CENTER><H3><A NAME="Heading35"></A><FONT COLOR="#000077">Using Braces in Nested if Statements</FONT></H3></CENTER><P>Although it is legal to leave out the braces on <TT>if</TT> statements that areonly a single statement, and it is legal to nest <TT>if</TT> statements, such as</P><PRE><FONT COLOR="#0066FF">if (x > y) // if x is bigger than y if (x < z) // and if x is smaller than z x = y; // then set x to the value in z</FONT></PRE><P>when writing large nested statements, this can cause enormous confusion. Remember,whitespace and indentation are a convenience for the programmer; they make no differenceto the compiler. It is easy to confuse the logic and inadvertently assign an <TT>else</TT>statement to the wrong <TT>if</TT> statement. Listing 4.7 illustrates this problem.</P><P><A NAME="Heading36"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 4.7. A demonstrationof why braces help clarify which else statement goes with which if statement.</B></FONT><FONTCOLOR="#0066FF"></FONT><PRE><FONT COLOR="#0066FF">1: // Listing 4.7 - demonstrates why braces2: // are important in nested if statements3: #include <iostream.h>4: int main()5: {6: int x;7: cout << "Enter a number less than 10 or greater than 100: ";8: cin >> x;9: cout << "\n";10:11: if (x > 10)12: if (x > 100)13: cout << "More than 100, Thanks!\n";14: else // not the else intended!15: cout << "Less than 10, Thanks!\n";16:17: return 0; <TT>18: }</TT></FONT><FONT COLOR="#0066FF">Output: Enter a number less than 10 or greater than 100: 20Less than 10, Thanks!</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis: </B></FONT>The programmer intended to ask fora number between 10 and 100, check for the correct value, and then print a thank-younote.<BR>If the <TT>if</TT> statement on line 11 evaluates <TT>TRUE</TT>, the following statement(line 12) is executed. In this case, line 12 executes when the number entered isgreater than 10. Line 12 contains an <TT>if</TT> statement also. This <TT>if</TT>statement evaluates <TT>TRUE</TT> if the number entered is greater than 100. If thenumber is not greater than 100, the statement on line 13 is executed.</P><P>If the number entered is less than or equal to 10, the <TT>if</TT> statement online 10 evaluates to <TT>FALSE</TT>. Program control goes to the next line followingthe <TT>if</TT> statement, in this case line 16. If you enter a number less than10, the output is as follows:</P><PRE><FONT COLOR="#0066FF">Enter a number less than 10 or greater than 100: 9</FONT></PRE><P>The <TT>else</TT> clause on line 14 was clearly intended to be attached to the<TT>if</TT> statement on line 11, and thus is indented accordingly. Unfortunately,the <TT>else</TT> statement is really attached to the <TT>if</TT> statement on line12, and thus this program has a subtle bug.</P><P>It is a subtle bug because the compiler will not complain. This is a legal C++program, but it just doesn't do what was intended. Further, most of the times theprogrammer tests this program, it will appear to work. As long as a number that isgreater than 100 is entered, the program will seem to work just fine. <BR><BR>Listing 4.8 fixes the problem by putting in the necessary braces.</P><P><A NAME="Heading38"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 4.8. A demonstrationof the proper use of braces with an if statement</B></FONT></P><PRE><FONT COLOR="#0066FF">1: // Listing 4.8 - demonstrates proper use of braces2: // in nested if statements3: #include <iostream.h>4: int main()5: {6: int x;7: cout << "Enter a number less than 10 or greater than 100: ";8: cin >> x;9: cout << "\n";10:11: if (x > 10)12: {13: if (x > 100)14: cout << "More than 100, Thanks!\n";15: }16: else // not the else intended!17: cout << "Less than 10, Thanks!\n";18: return 0;<TT>19: }</TT>Output: Enter a number less than 10 or greater than 100: 20</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis: </B></FONT>The braces on lines 12 and 15 makeeverything between them into one statement, and now the <TT>else</TT> on line 16applies to the <TT>if</TT> on line 11 as intended.<BR>The user typed <TT>20</TT>, so the <TT>if</TT> statement on line 11 is true; however,the <TT>if</TT> statement on line 13 is false, so nothing is printed. It would bebetter if the programmer put another <TT>else</TT> clause after line 14 so that errorswould be caught and a message printed.<BLOCKQUOTE> <P><HR><FONT COLOR="#000077"><B>NOTE:</B></FONT><B> </B>The programs shown in this book are written to demonstrate the particular issues being discussed. They are kept intentionally simple; there is no attempt to "bulletproof" the code to protect against user error. In professional-quality code, every possible user error is anticipated and handled gracefully. <HR></BLOCKQUOTE><CENTER><H3><A NAME="Heading40"></A><FONT COLOR="#000077">Logical Operators</FONT></H3></CENTER><P>Often you want to ask more than one relational question at a time. "Is ittrue that x is greater than y, and also true that y is greater than z?" A programmight need to determine that both of these conditions are true, or that some othercondition is true, in order to take an action.</P><P>Imagine a sophisticated alarm system that has this logic: "If the door alarmsounds AND it is after six p.m. AND it is NOT a holiday, OR if it is a weekend, thencall the police." C++'s three logical operators are used to make this kind ofevaluation. These operators are listed in Table 4.2.<BR><BR><FONT SIZE="4"><B>Table 4.2. The Logical Operators. </B></FONT><TABLE BORDER="0"> <TR ALIGN="LEFT" rowspan="1"> <TD ALIGN="LEFT"><B><I>Operator</I></B></TD> <TD ALIGN="LEFT"><B><I>Symbol</I></B></TD> <TD ALIGN="LEFT"><B><I>Example</I></B></TD> </TR> <TR ALIGN="LEFT" rowspan="1"> <TD ALIGN="LEFT"><TT>AND</TT></TD> <TD ALIGN="LEFT"><TT>&&</TT></TD> <TD ALIGN="LEFT">expression1<TT> && </TT>expression2</TD> </TR> <TR ALIGN="LEFT" rowspan="1"> <TD ALIGN="LEFT"><TT>OR</TT></TD> <TD ALIGN="LEFT"><TT>||</TT></TD> <TD ALIGN="LEFT">expression1<TT> || </TT>expression2</TD> </TR> <TR ALIGN="LEFT" rowspan="1"> <TD ALIGN="LEFT"><TT>NOT</TT></TD> <TD ALIGN="LEFT"><TT>!</TT></TD> <TD ALIGN="LEFT"><TT>!</TT>expression</TD> </TR></TABLE><CENTER><H4><A NAME="Heading41"></A><FONT COLOR="#000077">Logical AND</FONT></H4></CENTER><P>A logical <TT>AND</TT> statement evaluates two expressions, and if both expressionsare true, the logical <TT>AND</TT> statement is true as well. If it is true thatyou are hungry, AND it is true that you have money, THEN it is true that you canbuy lunch. Thus,</P><PRE><FONT COLOR="#0066FF">if ( (x == 5) && (y == 5) )</FONT></PRE><P>would evaluate <TT>TRUE</TT> if both <TT>x</TT> and <TT>y</TT> are equal to 5,and it would evaluate <TT>FALSE</TT> if either one is not equal to 5. Note that bothsides must be true for the entire expression to be true.</P><P>Note that the logical <TT>AND</TT> is two <TT>&&</TT> symbols. A single<TT>&</TT> symbol is a different operator, discussed on Day 21, "What'sNext."<CENTER><H4><A NAME="Heading42"></A><FONT COLOR="#000077">Logical OR</FONT></H4></CENTER><P>A logical <TT>OR</TT> statement evaluates two expressions. If either one is true,the expression is true. If you have money OR you have a credit card, you can paythe bill. You don't need both money and a credit card; you need only one, althoughhaving both would be fine as well. Thus,</P><PRE><FONT COLOR="#0066FF">if ( (x == 5) || (y == 5) )</FONT></PRE><P>evaluates <TT>TRUE</TT> if either <TT>x</TT> or <TT>y</TT> is equal to 5, or ifboth are.</P><P>Note that the logical <TT>OR</TT> is two <TT>||</TT> symbols. A single <TT>|</TT>symbol is a different operator, discussed on Day 21.<CENTER><H4><A NAME="Heading43"></A><FONT COLOR="#000077">Logical NOT</FONT></H4></CENTER><P>A logical <TT>NOT</TT> statement evaluates <TT>true</TT> if the expression beingtested is false. Again, if the expression being tested is false, the value of thetest is <TT>TRUE</TT>! Thus</P><PRE><FONT COLOR="#0066FF">if ( !(x == 5) )</FONT></PRE><P>is true only if <TT>x</TT> is not equal to 5. This is exactly the same as writing</P><PRE><FONT COLOR="#0066FF">if (x != 5)</FONT></PRE><CENTER><H3><A NAME="Heading44"></A><FONT COLOR="#000077">Relational Precedence</FONT></H3></CENTER><P>Relational operators and logical operators, being C++ expressions, each return
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -