|
|
|
|
|
|
|
Analysis: The programmer intended to ask for a number between 10 and 100, check for the correct value, and then print a thank you note. |
|
|
|
|
|
|
|
|
If the if statement on line 11 evaluates true, the following statement (line 12) is executed. In this case, line 12 executes when the number entered is greater than 10. Line 12 contains an if statement also. This if statement evaluates true if the number entered is greater than 100. If the number is not greater than 100, the statement on line 13 is executed. |
|
|
|
|
|
|
|
|
If the number entered is less than or equal to 10, the if on line 10 evaluates to false. Program control goes to the next line following the if, 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 |
|
|
|
|
|
|
|
|
The else clause on line 14 was clearly intended to be attached to the if statement on line 11, and thus is indented accordingly. Unfortunately, the else statement is really attached to the if 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 time 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. |
|
|
|
|
|
|
|
|
Listing 4.6 fixes the problem by putting in the necessary braces. |
|
|
|
|
|
|
|
|
LISTING 4.6 DEMONSTRATES THE PROPER USE OF BRACES WITH ANif STATEMENT |
|
|
|
 |
|
|
|
|
1: // Listing 4.6 - demonstrates proper use of braces
2: // in nested if statements
3: #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
17: cout << Less than 10, Thanks!\n;
18: return 0;
19: } |
|
|
|
|
|