16
Chapter 1
You can elaborate the
if
statement using
else if
and
else
statements.
These optional additions allow you to describe
more complicated branch-
ing behavior, as shown in Listing 1-3.
u
if (
boolean-expression-1
)
statement-1
v
else if (
boolean-expression-2
)
statement-2
w
else
statement-3
Listing 1-3: An
if
statement with
else if
and
else
branches
First,
boolean-expression-1
u
is evaluated. If
boolean-expression-1
is true,
statement-1
is evaluated, and the
if
statement stops executing. If
boolean
-expression-1
is false,
boolean-expression-2
v
is evaluated. If true,
statement-2
is evaluated. Otherwise,
statement-3
w
is evaluated. Note that
statement-1
,
statement-2
, and
statement-3
are mutually exclusive
and together they cover
all possible outcomes of the
if
statement. Only one of the three will be
evaluated.
You can include any number of
else if
clauses or omit them entirely. As
with the initial
if
statement, the
Boolean expression for each
else if
clause
is evaluated in order. When one of these Boolean expressions evaluates to
true
, evaluation stops and the corresponding statement executes. If no
else
if
evaluates to
true
, the
else
clause’s
statement-3
always executes. (As with
the
else if
clauses, the
else
is optional.)
Consider Listing 1-4, which uses an
if
statement to determine which
statement to print.
#include
int main() {
int x = 0;
u
if (x > 0) printf("Positive.");
else if (x < 0) printf("Negative.");
else printf("Zero.");
}
Zero.
Listing 1-4: A program with conditional behavior
Compile the program and run it. Your result should also be
Zero
. Now
change the
x
value
u
. What does the program print now?
N O T E
Notice that
main
in Listing 1-4 omits a return statement. Because
main
is a special
function, return statements are optional.
Dostları ilə paylaş: