Previous Up Next

12.3.2  The switch statement: switch case default

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 doesn’t equal any of the given integers:

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

(where recall 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 12.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:
Input:

oper(2,3,1)

Output:

5

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

oper(2,3,2)

Output:

−1

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


Previous Up Next