Anda di halaman 1dari 2

Switch Statement Page 1 of 2

Switch Statement
mikroC PRO for PIC Language Reference > Statements > Selection Statements >

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 compares it to all available
constant-expressions following the keyword case. If a match is found, switch passes control to that
matching case causing the statement following the match evaluates. Note that constant-expressions
must evaluate 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
evaluates (if the label default is specified).

For example, if a variable i has value between 1 and 3, the following switch would always return it as

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
code to the appopriate routine:

switch (phase) {
case 0: Lo(); break;
case 1: Mid(); break;

mk:@MSITStore:E:\Users\Public\Documents\Mikroelektronika\mikroC%20PRO%20f... 7/31/2016
Switch Statement Page 2 of 2

case 2: Hi(); break;

default: Message("Invalid state!");

Nested switch
Conditional switch statements can be nested – labels case and default are then assigned to the
innermost enclosing switch statement.

Copyright (c) 2002-2015 mikroElektronika. All rights reserved.Want more examples and libraries?
What do you think about this topic ? Send us feedback! Find them on

mk:@MSITStore:E:\Users\Public\Documents\Mikroelektronika\mikroC%20PRO%20f... 7/31/2016