Game Development Reference
In-Depth Information
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, then the instructions after
the default keyword are executed. The values behind the different cases need to be
constant values (numbers, characters, or strings between double quotes, or variables
declared as constant).
22.6.4 The break -Instruction
If we do not watch out, the switch -instruction not only executes the instruction be-
hind the relevant case, but also the instructions behind the other cases. This is pre-
vented by placing the special break -instruction after each case. The break -instruction
basically means: “stop executing the switch -, while -, or for -instruction that we are
currently in”. If we did not place any break -instruction in the example above, then
in the case that x==2 , the methods two and alsoTwo would be called, but also the
methods threeOrFour and more() .
In some cases, this behavior could be useful, so that, in a sense, the different
cases flow through each other. In languages related to C# such as C, C++ and Java,
this is indeed possible. However, it also leads to many errors, because if a pro-
grammer forgot to place a break -instruction somewhere, this would lead to very
strange behavior. C# broke with this tradition, and cases always have to be sep-
arated by a break -instruction, with one exception. You are allowed to write mul-
tiple case labels in front of a group of instructions, like we did in the example
with the cases 3 and 4. The syntax of the switch -instruction is a part of the in-
struction syntax diagram. This is the part of that diagram belonging to the switch -
instruction:
Search WWH ::




Custom Search