< previous page page_55 next page >

Page 55
second number yields no remainder. If so, the numbers are either evenly divisible or equal. The if statement on line 23 checks for equality and displays the appropriate message either way.
If the if statement on line 21 fails, the else statement on line 28 is executed.
Use Braces in Nested if Statements
It is legal to leave out the braces on if statements that are only a single statement, and it is legal to nest if statements, such as those shown below.
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 y
However, when you are writing large nested statements, this practice can cause enormous confusion. Remember, whitespace and indentation are a convenience for the programmer; they make no difference to the compiler. It is easy to confuse the logic and inadvertently assign an else statement to the wrong if statement. Listing 4.5 illustrates this problem.
LISTING 4.5 DEMONSTRATES WHY BRACES HELP CLARIFY WHICHelse STATEMENT GOES WITH WHICHif STATEMENT

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:   // Listing 4.5 - demonstrates why braces
2:   // are important 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:        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;
18:  }

Output:
Enter a number less than 10 or greater than 100: 20
Less than 10, Thanks!

 
< previous page page_55 next page >

If you like this book, buy it!