Switch Statement
Video Summary: https://youtu.be/_ZZ_HcCpsfE
The switch
statement is a selection statement that can be used
instead of a series of
if-else
statements.
Switch statements are often much simpler than if statements when there are many options.
Alternative statements are listed with
a label in front of each. A label can be either a case label
or a default label. A case label is the word case followed by
a constant integer expression, then a colon :
.
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 Statements
{
.
.
.
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 theswitch
's variable integer expression
- the letters A, B, C, D and F beside the
case
statements make up thecase
labels.
- the value in
grade
is compared with the value in eachcase
label. When a match is found, the corresponding statement is executed. If the value of theswitch
expression does not match a value in anycase
label, thedefault
label is matched by default.
- Because execution continues after a match until
break
is encountered, both 'D' and 'F' send the same message to the screen.- What would happen if we forgot to put
break
after the statements associated withcase 'b':
?
Every timegrade
contained a B both "Good work!" and "Passing work!" would be printed.
- What would happen if we forgot to put
Switch statements in c++ only work with integer and char cases, and will not work with strings. The only exception is if you use enumerators as shown in the bonus exercise