if, else Statements
**if(**expression )
statement1
[else
statement2]
The if keyword executes statement1 if expression is true (nonzero); if else is present and expression is false (zero), it executes statement2. After executing statement1 or statement2, control passes to the next statement.
For related information, see switch.
Example 1
if ( i > 0 )
y = x / i;
else
{
x = i;
y = f( x );
}
In this example, the statement y = x/i;
is executed if i
is greater than 0. If i
is less than or equal to 0, i
is assigned to x
and f( x )
is assigned to y
. Note that the statement forming the if clause ends with a semicolon.
When nesting if statements and else clauses, use braces to group the statements and clauses into compound statements that clarify your intent. If no braces are present, the compiler resolves ambiguities by associating each else with the closest if that lacks an else.
Example 2
if ( i > 0 ) /* Without braces */
if ( j > i )
x = j;
else
x = i;
The else clause is associated with the inner if statement in this example. If i
is less than or equal to 0, no value is assigned to x
.
Example 3
if ( i > 0 )
{ /* With braces */
if ( j > i )
x = j;
}
else
x = i;
The braces surrounding the inner if statement in this example make the else clause part of the outer if statement. If i
is less than or equal to 0, i
is assigned to x
.