The format of the following code if ( x < 10 )
y = x; z = x + 5;
implies that both assignments are part of the body of the ifstatement. Since multiple statements making up the body must be in a compound statement within curly braces, the compiler interprets the code fragment as if it had been written
if ( x < 10 ) y = x; z = x + 5;
Such code will optionally execute the first assignment statement and always exe- cute the second assignment statement.
The programmer probably meant to write it as if ( x < 10 )
{
y = x; z = x + 5; }
The curly braces are optional if the body consists of a single statement. If the body consists of only one statement and curly braces are not used, then the semicolon that terminates the statement in the body also terminates theifstatement. If curly braces are used to delimit the body, a semicolon is not required after the body’s close curly brace.
5.5
The if/else Statement
One undesirable aspect of Listing 5.2 (betterdivision.cpp) is if the user enters a zero divisor, nothing is printed. It may be better to provide some feedback to the user to indicate that the divisor provided cannot be used. Theifstatement has an optionalelseclause that is executed only if the Boolean expression is false. Listing 5.4 (betterfeedback.cpp) uses theif/elsestatement to provide the desired effect.
Listing 5.4: betterfeedback.cpp 1 #include <iostream> 2 3 using namespace std; 4 5 int main() 6 {
7 int dividend, divisor; 8
9 // Get two integers from the user
10 cout << "Please enter two integers to divide:"; 11 cin >> dividend >> divisor;
5.5. THE IF/ELSE STATEMENT 83
13 if ( divisor != 0 )
14 cout << dividend << "/" << divisor << " = "
15 << dividend/divisor << endl;
16 else
17 cout << "Division by zero is not allowed" << endl;
18 }
A given program run will execute exactly one of either the ifbody or theelse body. Unlike in Listing 5.2 (betterdivision.cpp), a message is always displayed.
Please enter two integers to divide: 32 0 Division by zero is not allowed
Theelseclause contains an alternate body that is executed if the condition is false. The program’s flow of execution is shown in Figure 5.2.
do the division and print result
Is divisor ≠ 0?
yes
no
castigate user
Figure 5.2: if/else flowchart
Listing 5.4 (betterfeedback.cpp) avoids the division by zero run-time error that causes the program to terminate prematurely, but it still alerts the user that there is a problem. Another application may handle the situation in a different way; for example, it may substitute some default value for divisor instead of zero.
5.5. THE IF/ELSE STATEMENT 84
if
(
condition )
if statement ;
else
else statement ;
• The reserved wordifbegins theif/elsestatement.
• The condition is a Boolean expression that determines whether or not theifstatement or theelse statement will be executed. The condition must be in parentheses.
• The if statement is the statement to be executed if the condition is true. To make theif/else statement more readable, the if statement is indented more spaces than theifline. This part of the ifstatement is sometimes called the body of theif.
• The reserved wordelsebegins the second part of theif/elsestatement.
• The else statement is the statement to be executed if the condition is false. To make theif/else statement more readable, the else statement is indented more spaces than theelseline. This part of theif/elsestatement is sometimes called the body of theelse.
The body of theelseclause of anif/elsestatement may be a compound statement: if ( x == y ) cout << x; else { x = 0; cout << y; }
or theifbody alone may be a compound statement: if ( x == y ) { cout << x; x = 0; } else cout << y;
or both parts may be compound: if ( x == y ) { cout << x; x = 0; } else { cout << y; y = 0; }
5.5. THE IF/ELSE STATEMENT 85
or, as in Listing 5.4 (betterfeedback.cpp), both theifbody and theelsebody can be simple statements.
Remember, if you wish to associate more than one statement with the body of theiforelse, you must use a compound statement. Compound statements are enclosed within curly braces ({}).
Due to the imprecise representation of floating-point numbers (see Listing 4.3 (imprecise10.cpp) in Sec- tion 4.1), the equality operator (==) by itself should not be used when comparing floating-point expressions. Listing 5.5 (samedifferent.cpp) uses anif/elsestatement to demonstrate the perils of using the equality operator with floating-point quantities.
Listing 5.5: samedifferent.cpp 1 #include <iostream> 2 #include <iomanip> 3 4 using namespace std; 5 6 int main() 7 { 8 double d1 = 1.11 - 1.10, 9 d2 = 2.11 - 2.10; 10 cout << "d1 = " << d1 << endl; 11 cout << "d2 = " << d2 << endl; 12 if ( d1 == d2 )
13 cout << "Same" << endl;
14 else
15 cout << "Different" << endl;
16 cout << "d1 = " << setprecision(20) << d1 << endl; 17 cout << "d2 = " << setprecision(20) << d2 << endl;
18 }
In Listing 5.5 (samedifferent.cpp) the displayed values of d1 and d2 are rounded so they appear equivalent, but internally the exact representations are slightly different. By including the header iomanip we can use the setprecision stream manipulator to force cout to display more decimal places in the floating- point number it prints. Observe from the output of Listing 5.5 (samedifferent.cpp) that the two quantities that should be identically 0.01 are actually slightly different.
d1 = 0.01 d2 = 0.01 Different
d1 = 0.010000000000000009 d2 = 0.0099999999999997868
This result should not discourage you from using floating-point numbers where they truly are needed. In Section 9.4.6 we will see how to handle floating-point comparisons properly.