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 case 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 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:

switch (phase) {
  case 0: Lo();  break;
  case 1: Mid(); break;
  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-2012 mikroElektronika. All rights reserved.
What do you think about this topic ? Send us feedback!
Want more examples and libraries? 
Find them on LibStock - A place for the code