< Previous | Contents | Next >
In the first if statement I test true. Because true is, well, true, the program displays the message, “This is always displayed.”
if (true)
{
cout << "This is always displayed.\n\n";
}
In the next if statement I test false. Because false isn’t true, the program doesn’t display the message, “This is never displayed.”
if (false)
{
cout << "This is never displayed.\n\n";
}
Tra p
Notice that you don’t use a semicolon after the closing parenthesis of the expression you test in an if statement. If you were to do this, you’d create an empty statement that would be paired with the if statement, essentially rendering the if statement useless. Here’s an example:
if (false);
cout << "This is never displayed.\n\n";
}
By adding the semicolon after (false), I create an empty statement that’s associated with the
if statement. The preceding code is equivalent to:
if (false)
; // an empty statement, which does nothing
{
cout << "This is never displayed.\n\n";
}
All I’ve done is play with the whitespace, which doesn’t change the meaning of the code. Now the problem should be clear. The if statement sees the false value and skips the next statement (the empty statement). Then the program goes on its merry way to the statement after the if statement, which displays the message, “This is never displayed.”
Be on guard for this error. It’s an easy one to make and because it’s not illegal, it won’t produce a compile error.