The switch
statement is a selection statement that can be used
instead of a series of
if-else if-else
statements.
Switch statements are often much simpler than if statements when there are many options.
:
.
The value of the switch
variable integer expression is used to match one of the values on the case
labels. The statement after the label that is matched is executed. Execution
continues sequentially from the matched label untill the end of the switch
statement is encountered or a break
statement is encountered.
Here is the syntax template for the switch
statement:
switch ( variable_integer_expression )
{
case constant_integer_expression : // there's usually at least one case label
// optional statements
//repeat case labels and statements as needed
.
.
.
default: // optional, can appear anywhere but only once per switch statement
// optional statements
}
variable_integer_expression is any expression of integral type -
char
,
int
,
long
,
bool
, or
enum
.
{
.
.
.
break; constant_integer_expression:
.
.
.
}
A break
statement will cause execution to
jump to the end of a block of statements. break
statements are often used to end case labels
in switch
statements.
Now let's look at an example:
switch (grade)
{
case 'A':
cout << "Great work. " << endl;
break;
case 'B':
cout << "Good work. " << endl;
break;
case 'C':
cout << "Passing work. " << endl;
break;
case 'D':
case 'F':
cout << "Unsatisfictory work. " << endl;
cout << "See your instructor." << endl;
break;
default:
cout << grade << " is not a legal grade." << endl;
break;
}
grade
is the switch
's variable integer expressioncase
statements make up the case
labels. grade
is compared with the value in each case
label.
When a match is found, the corresponding statement is executed.
If the value of the switch
expression does not match a value in any case
label,
the default
label is matched by default. break
is encountered, both 'D' and 'F' send the same
message to the screen.
break
after the statements associated with case 'b':
? grade
contained a B both "Good work!" and "Passing work!"
would be printed.
©Department of Computer Science, University of Regina.