The if statement evaluates the expression enclosed in parentheses. The expression must be of arithmetic or pointer type, or it must be of a class type that defines an unambiguous conversion to an arithmetic or pointer type. (For information about conversions, see Chapter 3, Standard Conversions.)
In both forms of the if syntax, if the expression evaluates to a nonzero value (true), the statement dependent on the evaluation is executed; otherwise, it is skipped.
In the if...else syntax, the second statement is executed if the result of evaluating the expression is zero.
The else clause of an if...else statement is associated with the closest previous if statement that does not have a corresponding else statement. The following code fragment demonstrates how this works:
if( condition1 == true )
if( condition2 == true )
cout << "condition1 true; condition2 true\n";
else
cout << "condition1 true; condition2 false\n";
else
cout << "condition 1 false\n";
Many programmers use curly braces ({ }) to explicitly clarify the pairing of complicated if and else clauses, such as in the following example:
if( condition1 == true )
{
if( condition1 == true )
cout << "condition1 true; condition2 true\n";
else
cout << "condition1 true; condition2 false\n";
}
else
cout << "condition 1 false\n";
Although the braces are not strictly necessary, they clarify the pairing between if and else statements.