Statement
switch(E)
{
case 0:
statements
break;
case 1:
statements
break;
...
default:
statements
}
computes the value of expression E, which must be an integer or character or
a value of an enumerated type.
(Recent versions of C++ allow it to be a string as well. C does not allow strings
in switches. Avoid using strings in switches.)
Then it chooses a case depending on
the value of E. For example, if the value of E is 0 then
the statements for the case labeled 0 are performed. If E is not the
value listed in any of the case, the statements after default: are
performed.
Case labels in a switch must be constants
The cases can cover any desired collection of values, in any order, but
the values following case must be constants. For example,
switch(x)
{
case y:
...
}
is not allowed.
|
Default is optional
| If you omit the default: case, the switch statement will do nothing if E is not a value indicated by any of the cases. |
Break statements in a switch
| The statements for each case are followed by a break-statement, which ends the switch statement. If you omit the break-statement, then the program keeps going, performing the code for the case that follows. Although that is sometimes what you want, it is usually not. The coding standards for this course require a break after each case except the last, unless the case ends on a return statement. |
Sharing code for more than one value
You can label one group of statements by more than one case value.
Example:
switch(x)
{
case 1:
case 2:
printf("x is either 1 or 2\n");
break;
case 3:
case 4:
printf("x is either 3 or 4\n");
break;
default:
printf("x is not 1, 2, 3 or 4\n");
break;
}
|