Syntax: Switch Case

The switch case function allows you to perform a set of actions based on one or more from a set of conditions. It is like having a series of if…else statements. It allows you to check a variable for several values at once and then perform actions based on the current value.

At the end should be a special case called default which is what happens if the variable doesn’t macth any of the specific cases.

 

Syntax

switch(variable to check)

{

case n:

list of actions if the variable equals n

break;

case m:

list of actions if the variable equals m

break;

 

default:

list of actions for all other cases

break;

}

Note that the function "falls through" this means that after performing the list of actions for a particular case, the function will move to the next case and perform those actions too. If you only want the actions for one case to be performed you need to break out of the switch case statement at the end of the relevant actions by including the command break; as in the example above.

Note:
You can use return in place of break which will leave the entire function in which the switch case statement is contained while break just jumps to the end of the switch case statement itself allowing the function to contain other statements or expressions.

Thus in the following script if the variable contains A then it will perfom the actions for A and the actions for B and the actions for default.

 

switch(variable to check)

{

case "A":

  // list of actions if the variable equals A

case "B":

  // list of actions if the variable equals B

default:

  // list of actions for all other cases

break;

  }

 

This fall through also means that individual cases do not need to contain any expressions, they can be empty blocks. They can simply be used to include themselves in a set of actions performed by a subsequent case.

 

switch(numbersToCheck)

{

case 1:

case 3:

case 5:

default:

return "odd number"

}

Note that unlike C++ the case block can be an expression (the example supposes x and y have been given values elsewhere).

 

switch(x)

{

case y+1:

  // actions to be taken if x is one more than y

break;

case y-1:

  // actions to be taken if x is one less than y

  break;

case y+3:

  // actions to be taken if x is three more than y

break;

default:

   // list of actions for all other cases

  }

 

image\Script_Button.jpgExamples