Sometimes you want to make several tests of a single value. C/C++
provides a switch statement for that purpose. Here is an example.
switch (x) {
case -1:
printf("Less than zero\n");
break;
case 0:
printf("Equal to 0\n");
break;
case 1:
printf("Greater than 0\n");
break;
default:
printf("Not one of the things I know about\n");
}
Caution: You must include
break; after each case. If you do not, then the program
will keep going into the next case. For example, if you run the
following with day = 5
switch(day) {
case 5:
printf("five gold rings\n");
case 4:
printf("four calling birds\n");
case 3:
printf("three french hens\n");
case 2:
printf("two turtledoves\n");
case 1:
printf("and a partridge in a pear tree\n");
}
the program prints
five gold rings
four calling birds
three french hens
two turtledoves
and a partridge in a pear tree
Note: If there is no default case, then nothing is done
if none of the cases match.
Note: You can have two or more cases do the same thing.
Just put them in a row, as in
case 4:
case 5:
text for these cases
Note: You can only use a switch when the type of the value
being tested is an integer type.
|