6.2 else Statement
An
alternative form of the if statement
is:
if (condition)
statement;
else
statement;
If the condition is true, the first statement is executed. If it is
false, the second statement is executed. In our accounting example,
we wrote out a message only if nothing was owed. In real life, we
probably want to tell the customer how much he owes if there is a
balance due.
if (total_owed <= 0)
std::cout << "You owe nothing.\n";
else
std::cout << "You owe " << total_owed << " dollars\n";
 |
Note
to Pascal programmers: Unlike Pascal, C++ requires you to put a
semicolon at the end of the statement before the else.
|
|
Now consider this program fragment:
if (count < 10) // If #1
if ((count % 4) == 2) // If #2
std::cout << "Condition:White\n";
else // (Indentation is wrong)
std::cout << "Condition:Tan\n";
There are two if statements and one
else. To which
if does the else belong? Pick one:
It belongs to if #1.
It belongs to if #2.
You don't have to worry about this situation if you
never write code like this.
The correct answer is 3. According to the C++ syntax rules, the
else goes with the nearest if, so 2 is syntactically correct. But writing
code like this violates the KISS principle (Keep It Simple, Stupid).
It is best to write your code as clearly and simply as possible. This
code fragment should be written as follows:
if (count < 10) { // If #1
if ((count % 4) == 2) // If #2
std::cout << "Condition:White\n";
else
std::cout << "Condition:Tan\n";
}
From our original example, it was not clear which if statement had the else clause; however, adding an extra set of
braces improves readability, understanding, and clarity.
|