|
  
switch
If you have a large number of conditionals that depend on the
value of a single variable, it is often more convenient to use a switch
statement than it is to use a long list of if/else statements.
The switch statement has the format
switch( expression ) {
case value1:
statement1
break;
case value2:
statement2
break;
. . .
default:
statement3
}
This is best illustrated by example. The following switch
statement converts an integer value n to a text
representation of the integer:
switch(n) {
case 0:
name="zero";
break;
case 1:
name="one";
break;
case 2:
name="two";
break;
case 3:
name="three";
break;
case 4:
name="four";
break;
case 5:
name="five";
break;
case 6:
name="six";
break;
case 7:
name="seven";
break;
case 8:
name="eight";
break;
case 9:
name="nine";
break;
default:
name="ERROR: n is not between 0 and 9";
}
This statement first evaluates the expression n and
then scans all case statements to find one that matches the value
of n. For example, if n is equal to 3, execution of
the conditional statements begins at case 3:.
In the example, all you want to do for each case is set the value
of the variable called name and then jump out of the case
statement. You jump out of the statement using the break
command. If none of the case statements contains a match for the
value of n, execution jumps to default:.
Note that execution of the conditional statements starts at
the matching case statement, but does not end with the start of
the next case statement. For example, if you remove the break
command between the third and fourth cases, as follows:
case 3:
name="three";
case 4:
name="four";
break;
When n is equal to 3, the variable name will be
set equal to three and then
execution will chain into the next case statement. That is, name
will be changed to be equal to four.
You can intentionally use this feature to combine cases as in
the following example:
switch(n) {
case 0:
case 2:
case 4:
case 6:
case 8:
name="even number";
break;
case 1:
case 3:
case 5:
case 7:
case 9:
name="odd number";
break;
default:
name="ERROR: n is not between 0 and 9";
}
The individual case values can be any data type, not just
numbers. All of the following are legal case expressions:
case 3:
case 2.78:
case "number":
case true:
case [1,2,3]:
case 2+3:
case f(x)+g(y):
|