|
|
|
|
|
|
|
We code this information with an If-Then-Else nested within an If-Then: |
|
|
|
|
|
|
|
|
if (average < 70.0)
if (average < 60.0)
cout << Failing;
else
cout << Passing but marginal; |
|
|
|
|
|
|
|
|
How do we know to which if the else belongs? Here is the rule that the C++ compiler follows: In the absence of braces, an else is always paired with the closest preceding if that doesn't already have an else paired with it. We indented the code to reflect this pairing. |
|
|
|
|
|
|
|
|
Suppose we write the fragment like this: |
|
|
|
|
|
|
|
|
if (average >= 60.0) // Incorrect version
if (average < 70.0)
cout << Passing but marginal;
else
cout << Failing; |
|
|
|
|
|
|
|
|
Here we want the else branch attached to the outer If statement, not the inner, so we indent the code as you see it. But indentation does not affect the execution of the code. Even though the else aligns with the first if, the compiler pairs it with the second if. An else that follows a nested If-Then is called a dangling else. It doesn't logically belong with the nested If but is attached to it by the compiler. |
|
|
|
|
|
|
|
|
To attach the else to the first if, not the second, you can turn the outer then-clause into a block: |
|
|
|
|
|
|
|
|
if (average >= 60.0) // Correct version
{
if (average < 70.0)
cout << Passing but marginal;
}
else
cout << Failing; |
|
|
|
|
|
|
|
|
The { } pair indicates that the inner If statement is complete, so the else must belong to the outer if. |
|
|
|
|
|