Switch statements


Martin McBride, 2017-02-03
Tags none
Categories none

Switch statements are another type of selection, sometimes used instead of if statements.

Sometimes you might need to check the value of a variable, and do different things depending on the specific value of the variable.

For example, the GETKEY function returns a CHAR value such as 'A', 'B' or 'C' depending on which key is pressed on the keyboard. If we are coding a game, we might want out character to move in different directions depending on the key. Often the W, A, S and D keys are used for this.

You could use a set of elseif clauses to do this, but using a switch statement is often better.

Switch statements

Here is how we would implement the direction controls in a game using a switch statement:

CHAR key = GETKEY()
SWITCH key
    CASE 'W':
        moveForward()
    CASE 'A':
        moveLeft()
    CASE 'S':
        moveBack()
    CASE 'D':
        moveRight()
    DEFAULT:
        //Do nothing
ENDSWITCH

Here is how it works. The GETKEY function returns the character of whichever key is currently pressed.

The SWITCH statement includes a number of CASE statements. Depending on the value of key, it will run the code in one of the statements. If key contains the character 'W', it will call the moveForward function. If key contains the character 'A', it will call the moveLeft function, etc.

If key contains a value which does not have a CASE statement, the DEFAULT case will run instead. In this case it will do nothing, but it could do something else such as beep or show a warning.

Copyright (c) Axlesoft Ltd 2020