Sams Teach Yourself C++ in 21 Days

(singke) #1
Creating Expressions and Statements 89

4


Enter a number less than 10 or greater than 100: 20

Less than 10, Thanks!
The programmer intended to ask for a number less than 10 or greater than 100,
check for the correct value, and then print a thank-you note.
When the ifstatement on line 11 evaluates true, the following statement (line 12) is exe-
cuted. In this case, line 12 executes when the number entered is greater than 10. Line 12
contains an ifstatement also. This ifstatement evaluates true if the number entered is
greater than 100. If the number is greater than 100, the statement on line 13 is executed,
thus printing out an appropriate message.
If the number entered is less than 10, the ifstatement on line 11 evaluates false.
Program control goes to the next line following the ifstatement, in this case line 16. If
you enter a number less than 10, the output is as follows:
Enter a number less than 10 or greater than 100: 9
As you can see, there was no message printed. The elseclause on line 14 was clearly
intended to be attached to the ifstatement on line 11, and thus is indented accordingly.
Unfortunately, the elsestatement is really attached to the ifstatement on line 12, and
thus this program has a subtle bug.
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 the programmer tests
this program, it will appear to work. As long as a number that is greater than 100 is
entered, the program will seem to work just fine. However, if you enter a number from
11 to 99, you’ll see that there is obviously a problem!
Listing 4.8 fixes the problem by putting in the necessary braces.

LISTING4.8 A Demonstration of the Proper Use of Braces with an ifStatement


1: // Listing 4.8 - demonstrates proper use of braces
2: // in nested if statements
3: #include <iostream>
4: int main()
5: {
6: int x;
7: std::cout << “Enter a number less than 10 or greater than 100: “;
8: std::cin >> x;
9: std::cout << “\n”;
10:
11: if (x >= 10)
12: {
13: if (x > 100)

OUTPUT


ANALYSIS
Free download pdf