User manual
mikroPascal PRO for PIC32
MikroElektronika
225
Case Statement
Use the case statement to pass control to a specic program branch, based on a certain condition. The case statement
consists of a selector expression (a condition) and a list of possible values. The syntax of the case statement is:
case selector of
value_1 : statement_1
...
value_n : statement_n
[else default_statement]
end;
selector is an expression which should evaluate as integral value. values can be literals, constants, or expressions,
and statements can be any statements.
The else clause is optional. If using the else branch, note that there should never be a semicolon before the keyword
else.
First, the selector expression (condition) is evaluated. Afterwards the case statement compares it against all available
values. If the match is found, the statement following the match evaluates, and the case statement terminates. In
case there are multiple matches, the rst matching statement will be executed. If none of values matches selector, then
default_statement in the else clause (if there is some) is executed.
Here’s a simple example of the case statement:
case operator of
'*' : result := n1 * n2;
'/' : result := n1 / n2;
'+' : result := n1 + n2;
'-' : result := n1 - n2
else result := 0;
end;
Also, you can group values together for a match. Simply separate the items by commas:
case reg of
0: opmode := 0;
1,2,3,4: opmode := 1;
5,6,7: opmode := 2;
end;
In mikroPascal PRO for PIC32, values in the case statement can be variables too:
case byte_variable of
byte_var1: opmode := 0; // this will be compiled correctly
byte_var2:
opmode := 1; // avoid this case, compiler will parse
// a variable followed by colon sign as label
byte_var3: // adding a comment solves the parsing problem
opmode := 2;
end;
Nested Case statement
Note that the case statements can be nested – values are then assigned to the innermost enclosing case statement.