HP C A.06.05 Reference Manual
Statements
if
Chapter 6170
else if (exp3)
statement3
.. .
else
statement N
The important thing to remember is that C executes at most only one statement in the
if…else and if…else/if…else constructions. Several expressions may indeed be true, but
only the statement associated with the first true expression is executed.
Example 2
Expressions subsequent to the first true expression are not evaluated. For example:
/* determine reason the South lost the American Civil War */
if (less_money)
printf("It had less money than the North.\n");
else if (fewer_supplies)
printf("It had fewer supplies than the North.\n");
else if (fewer_soldiers)
printf("It had fewer soldiers.\n");
else
{
printf("Its agrarian society couldn't compete with the ");
printf("North's industrial one.\n");
}
All the expressions in the above code fragment could be evaluated to true, but the run-time
system would only get as far as the first line and never even test the remaining expressions.
Using Braces in Compound if Statements
Use curly braces ({ }) in a compound statement to indicate where the statement begins and
ends. For example:
if (x > y) {
temp = x;
x = y;
y = temp;
}
else
/* make next comparison */