The Dangling else

When an else is encountered in the code, it is paired with the closest preceding if that has not yet been paired. The if and else must be in the same block. The formatting (indentation) is irrelevant.

Consider this example. If average is 95, what is printed? If average is 65, what is printed?

if (average < 90)
   if (average < 60)
     cout << "Failing";
else
   cout << "An A student!";

To fix the example, you must use curly braces to tell the compiler to match the first if:

if (average < 90)
{
   if (average < 60)
     cout << "Failing";
}
else
   cout << "An A student!";

The else matches the first if because the second if is not in the same block as the else.

Next page
Previous page
Go to Lesson 7 index.


HTML by Jennifer Keiser.
Sponsored by Inspiration, the diagramming and outlining tool.