HP C/iX Reference Manual (31506-90011)
Chapter 6 85
Statements
The if Statement
The if Statement
The if statement executes a statement depending on the evaluation of an expression.
Syntax
if (
expression
)
statement
if (
expression
)
statement
else
statement
Description
The if statement is for testing values and making decisions. An if statement can
optionally include an else clause. For example:
if (j<1)
func(j);
else
{
j=x++;
func(j);
}
The first statement is executed only if the evaluated expression is true (i.e., evaluates to a
nonzero value). The expression may be of any scalar type. Note that expressions involving
relational expressions actually produce a result and may therefore be used in an if
statement.
If you include the else clause, the statement after the else is executed only if the
evaluated expression is false (i.e., evaluates to a zero value). Under no circumstances are
both statements in an if-else statement executed (unless you include a goto statement
from one substatement to the other).
If the first substatement is entered as the result of a goto to a label, the second
substatement (if provided) is not executed.
The "dangling else" problem associated with if statements of this form is resolved by
associating the else with the last lexically preceding if (without an else) that is in the
same block, but not in an enclosed block.
The else-if construction is useful to include more than one alternative to the if
statement. The following is an example of a three-way branch using the else-if chain:
if(a==b)
k=1;
else if(a==c)
k=2;
else if(a==d)
k=4;
Regardless of the relationships between the variables a, b, and c, only one statement
assigning a value to k is executed. You should use the else-if chain in place of the switch
statement when the controlling expressions are not constant expressions. However,
nesting too many else-if statements can make a program cumbersome.