Select Case Statement

Use the select case statement to pass control to a specific program branch, based on a certain condition. The select case statement consists of selector expression (condition) and list of possible values. The syntax of the select case statement is:

select case selector
  case value_1
    statements_1
  ...
  case value_n
    statements_n
  [case else
    default_statements]
end select

selector is an expression which should evaluate as integral value. values can be literals, constants or expressions and statements can be any statements. The case else clause is optional.

First, the selector expression (condition) is evaluated. The select case statement then compares it against all available values. If the match is found, the statements following the match evaluate, and the select case statement terminates. In case there are multiple matches, the first matching statement will be executed. If none of the values matches the selector, then default_statements in the case else clause (if there is one) are executed.

Here is a simple example of the select case statement:

select case operator
  case "*"
    res = n1 * n2
  case "/"
    res = n1 / n2
  case "+"
    res = n1 + n2
  case "-"
    res = n1 - n2
  case else
    res = 0
    cnt = cnt + 1
end select

Also, you can group values together for a match. Simply separate the items by commas:

select case reg
  case 0
    opmode = 0
  case 1,2,3,4
    opmode = 1
  case 5,6,7
    opmode = 2
end select

Nested Case Statements

Note that the select case statements can be nested – values are then assigned to the innermost enclosing select case 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