Switch statement

Game Maker 8

Switch statement

In a number of situations you want to let your action depend on a particular value. You can do this using a number of if statements but it is easier to use the switch statement. A switch statement has the following form:

switch (<expression>)
{
  case <expression1>: <statement1>; ... ; break;
  case <expression2>: <statement2>; ... ; break;
  ...
  default: <statement>; ...
}

This works as follows. First the expression is executed. Next it is compared with the results of the different expressions after the case statements. The execution continues after the first case statement with the correct value, until a break statement is encountered. If no case statement has the right value, execution is continued after the default statement. (It is not required to have a default statement.) Note that multiple case statements can be placed for the same statement. Also, the break is not required. If there is no break statement the execution simply continues with the code for the next case statement.

Example The following program takes action based on a key that is pressed.

switch (keyboard_key)
{
  case vk_left:
  case vk_numpad4:
    x -= 4; break;
  case vk_right:
  case vk_numpad6:
    x += 4; break;
}