Switch, While, for and do-while loops, Switch -26 while, for and do-while loops -26 – Rockwell Automation 2098-IPD-xxx Ultra5000 C Programming using the Motion Library User Manual

Page 38

Advertising
background image

Publication 2098-PM001E-EN-P — July 2002

1-26

Programming Motion Control in C

Switch

The switch statement performs a multiple path decision. It tests
whether an expression matches one of several constant integer values,
and branches accordingly. If no expression value matches, control
passes through each case until the default statement is encountered,
or no action takes place when the default option is absent.

switch (expression)

{

case expression1 : statement1;

case expression2 : statement2;

default

: statement3;

}

Of course this assumes that each case is unique.

When control passes to a specific case, all subsequent cases in the
switch command are performed until the end of the switch, or a break
statement, is encountered, whichever occurs first.

switch (expression)

{

case expression1 : statement1;

break;

/* if 1 runs, break

forces exit */

case expression2 : statement2;

break;

/* if 2 runs, break

forces exit */

default: statement3;

break;

/* break exits upon

default */

}

The break statement also forces an immediate exit from while, for,
and do loops.

While, For and Do-While Loops

The while statement creates a loop that repeats until the test
expression is false (zero).

while (expression)

statement;

/* if expression is

non-zero, loop until

zero */

The for statement contains three expressions to control a loop. The
initialization (expression1) is performed once, before any of the loop
expressions are evaluated. If the test (expression2) is true (nonzero),

Advertising