Game Development Reference
In-Depth Information
The
switch
instruction has a few handy properties that make it very useful for handling different
alternatives. Have a look at the following code example:
if (x === 1)
one();
else if (x === 2) {
two();
alsoTwo();
} else if (x === 3 || x === 4)
threeOrFour();
else
more();
You can rewrite this with a
switch
instruction as follows:
switch(x) {
case 1: one();
break;
case 2: two();
alsoTwo();
break;
case 3:
case 4: threeOrFour();
break;
default: more();
break;
}
When a
switch
instruction is executed, the expression between the parentheses is calculated.
Then the instructions after the word
case
and the particular value are executed. If there is no case
that corresponds to the value, the instructions after the
default
keyword are executed. The values
behind the different cases need to be constant values (numbers, characters, strings between double
quotes, or variables declared as constant).
The
break
Instruction
If you aren't careful, the
switch
instruction will execute not only the instruction behind the relevant
case but also the instructions behind the other cases. You can prevent this by placing the special
break
instruction after each case. The
break
instruction basically means, “Stop executing the
switch
,
while
, or
for
instruction you're currently in.” If there was no
break
instruction in the previous
example, then in the case
x === 2
, the methods
two
and
alsoTwo
would be called, and also the
methods
threeOrFour
and
more
.
In some cases this behavior is useful, so that, in a sense, the different cases flow through each
other. You have to watch out when doing this, though, because it can lead to errors—for instance,
if a programmer forgot to place a
break
instruction somewhere, this would lead to very strange
behavior. When you use the
switch
instruction, do it in such a way that cases are always separated
by
break
instructions. The only exception is when you write multiple
case
labels in front of a group
Search WWH ::
Custom Search