The C Programming Language, Ansi C
if (n > 0)
if (a > b)
z = a;
else
z = b;
the
else
goes to the inner
if
, as we have shown by indentation.
If that isn't what you want, braces must be used to force the proper
association:
if (n > 0) {
if (a > b)
z = a;
}
else
z = b;
The ambiguity is especially pernicious in situations like this:
if (n > 0)
for (i = 0; i < n; i++)
if (s[i] > 0) {
printf("...");
return i;
}
else /* WRONG */
printf("error -- n is negativen");
The indentation shows unequivocally what you want, but the compiler doesn't
get the message, and associates the
else
with the inner
if
.
This kind of bug can be hard to find; it's a good idea to use braces when
there are nested
if
s.
By the way, notice that there is a semicolon after z = a in
if (a > b)
z = a;
else
z = b;
This is because grammatically, a
statement
follows the
if
,
and an expression statement like
z = a;
'' is always terminated by a
semicolon.
The construction
if (
expression
)
statement
else if (
expression
)
statement
else if (
expression
)
statement
else if (
expression
)
statement
else
statement
occurs so often that it is worth a brief separate discussion. This sequence
of
if
statements is the most general way of writing a multi-way
decision. The
expressions
are evaluated in order; if an
expression
is true, the
statement
associated with it is
executed, and this terminates the whole chain. As always, the code for each
statement
is either a single statement, or a group of them in braces.
The last else part handles the none of the above'' or default case where none of the other conditions is satisfied. Sometimes there is no explicit action for the default; in that case the trailing
else
statement
can be omitted, or it may be used for error checking to catch an
impossible'' condition.