Name
if ... else
Synopsis
The if
statement creates a
conditional jump.
Syntax:
if (expression
)
statement1
[else
statement2
]
The
expression
must have a scalar type. First, the if
statement’s controlling expression is evaluated. If
the result is not equal to 0
—in other words,
if the expression yields
“true”—then
statement1
is executed. Otherwise, if
else
is present,
statement2
is executed.
Example:
if (x > y) max = x; // Assign the greater of x and y to else max = y; // the variable max.
The use of else
is optional. If the value of the
controlling expression is 0
, or
“false”, and
else
is omitted, then the program execution
continues with the next statement.
If several if
statements are nested, then an
else
clause always belongs to the last
if
(in the given block nesting level) that does
not yet have an else
clause. An
else
can be assigned to a different
if
by creating explicit blocks.
Example:
if ( n > 0 { if ( n % 2 == 0 puts("n is positive and even"); } else // Belongs to first if puts("n is negative or zero");
Get C Pocket Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.