Switch statement

### 25.3.2 Switch statement

The switch statement can be used when you want the value of a block to depend on an integer. It takes one argument, an expression which evaluates to an integer. It should be followed by a sequence of case statements, which takes the form case followed by an integer and then a colon, which is followed by a code block to be executed if the expression equals the integer. At the end is an optional default statement, which is followed by a code block to be executed if the expression does not equal any of the given integers.

switch(n) {
case n1: block n1
case n2: block n2
…
case nk: block nk
default: default_block

Recall that the blocks need to be delimited by braces or by begin and end.

#### Example

As an example of a program which performs an operation on the first two variables depending on the third, you could enter (see Section 25.1.1):

oper(a,b,c):={ switch (c) { case 1: { a:=a+b; break; } case 2: { a:=a-b; break; } case 3: { a:=a*b; break; } default: { a:=a^b; } } return a; }

Then:

oper(2,3,1)

5 |  |  |  |  |  |  |  |  |  |

since the third argument is 1, and so oper(a,b,c) will return a+b, and:

oper(2,3,2)

−1 |  |  |  |  |  |  |  |  |  |

since the third argument is 2 and so oper(a,b,c) will return a−b.