Datasheet
SWITCH STATEMENT
The switch statement is used to pass control to a specific program branch, based
on a certain condition. The syntax of the switch statement is:
switch (expression) {
case constant-expression_1 : statement_1;
.
.
.
case constant-expression_n : statement_n;
[default : statement;]
}
First, the expression (condition) is evaluated. The switch statement then com-
pares it to all available constant-expressions following the keyword case. If a
match is found, switch passes control to that matching case causing the state-
ment
following the match evaluates. Note that constant-expressions must evalu-
ate to integer. It is not possible to have two same constant expressions evaluating
to the same value.
Parentheses around expression are mandatory.
Upon finding a match, program flow continues normally: the following instructions
will be executed in natural order regardless of the possible
case label. If no case
satisfies the condition, the default case evaluates (if the label default is speci-
fied).
For example, if a variable i has value between 1 and 3, the following switch would
always return it as 4:
switch (i) {
case 1: i++;
case 2: i++;
case 3: i++;
}
To avoid evaluating any other cases and relinquish control from switch, each case
should be terminated with break.
Here is a simple example with switch. Suppose we have a variable phase with only
3 different states (0, 1, or 2) and a corresponding function (event) for each of these
states. This is how we could switch the code to the appopriate routine:
211
MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
Language Reference
mikroC PRO for AVR
CHAPTER 5