Sams Teach Yourself C++ in 21 Days

(singke) #1
If the first ifis true, the block of code beginning on line 22 is executed, and a second if
statement is tested on line 23. This checks to see whether the first number divided by the
second number yields no remainder. If so, the numbers are either evenly divisible or
equal. The ifstatement on line 25 checks for equality and displays the appropriate mes-
sage either way.
If the ifstatement on line 23 fails (evaluates to false), then the elsestatement on line 30
is executed.

Using Braces in Nested ifStatements ..................................................................


Although it is legal to leave out the braces on ifstatements that are only a single state-
ment, and it is legal to nest ifstatements, doing so can cause enormous confusion. The
following is perfectly legal in C++, although it looks somewhat confusing:
if (x > y) // if x is bigger than y
if (x < z) // and if x is smaller than z
x = y; // set x to the value in y
else // otherwise, if x isn’t less than z
x = z; // set x to the value in z
else // otherwise if x isn’t greater than y
y = x; // set y to the value in x
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
elsestatement to the wrong ifstatement. Listing 4.7 illustrates this problem.

LISTING4.7 A Demonstration of Why Braces Help Clarify Which elseStatement Goes
with Which ifStatement
1: // Listing 4.7 - demonstrates why braces
2: // are important 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: if (x > 100)
13: std::cout << “More than 100, Thanks!\n”;
14: else // not the else intended!
15: std::cout << “Less than 10, Thanks!\n”;
16:
17: return 0;
18: }

88 Day 4

Free download pdf