Testing expressions: if, Selection: switch – Crunch CRiSP File Editor 6 User Manual

Page 29

Advertising
background image

Page 29

The init-expr is evaluated first. Next the while-expr is evaluated, and if it evaluates to TRUE, then statement
is executed. After statement is executed, post-expr is executed. The loop continues until while-expr
evaluates to FALSE. Any combination of the init-expr, while-expr, and post-expr may be omitted, as in
standard C. If while-expr is omitted, then the loop will execute indefinitely. In this case the only way to
terminate the loop is if the statement part of the loop contains a return or break clause.

The while looping construct has the syntax:

while (expr)
statement

expr is evaluated and if it evaluates to non-zero, then statement is evaluated. This process is repeated until
expr evaluates to FALSE, or the statement clause causes an exit from the loop (either via break or return).
While loops always evaluate the expr clause at least once.

The do looping construct has the syntax:

do
statement
while (expr)

In this case, the statement clause is executed first, and the expr clause is tested after the body of the loop
has been executed. Do loops are useful when you need to guarantee that the body of the loop is executed
at least once.

{button See Also, ALink(crunch,,,)}

Testing expressions: if

The if statement is used to execute a piece of code conditionally. The syntax is:

if (expr)
statement-1
[else
statement-2]

The expr is evaluated and if it is non-zero, then statement-1 is evaluated. If expr evaluates to zero (false),
and if the else clause is present, then statement-2 is executed instead.

Crunch also supports the tertiary '?..:' operator which can be used inside expressions, for example:

int a = b > c ? b : c;

{button See Also, ALink(crunch,,,)}

Selection: switch

The switch statement is a compact and fast mechanism for selecting a statement to execute depending on
the value of some expression. The general syntax is:

switch (expr) {
case expr-1:
statement-list-1
case expr-2:
statement-list-2
...
default:
statement-list-n
}

Switch statements look and almost feel like C switch statements. Switches are interpreted as follows: expr is
evaluated and tested for equality against expr-1. If it matches, then statement-list-1 is executed and
execution continues after the switch statement. If the match fails, expr-2 is tested, and so on until either a
match is found, the default clause is reached or no entry is found. If no entry is found, then execution
continues after the switch statement. If the default clause is reached, then the statements there are
executed.

Crunch allows multiple cases to be associated with a single statement:

switch (expr) {

Advertising