switch and case
This lesson introduces switch and case statements, how and when they are used and the implementation of the final switch statement.
We'll cover the following
switch
and case
#
switch
is a statement that allows comparing the value of an expression against multiple possible values. It is similar to but not the same as an "if
, else if
, else
" chain. case
is used for specifying which values are to be compared with switch’s expression. It is only a part of switch statement and not a statement itself.
switch
takes an expression within parentheses, compares the value of that expression to the case
values and executes the operations of the case
that is equal to the value of the expression. Its syntax consists of a switch
block that contains one or more case
sections and a default
section:
switch (expression) {
case value_1:
// operations to execute if the expression is equal to value_1
// ...
break;
case value_2:
// operations to execute if the expression is equal to value_2
// ...
break;
// ... other cases ...
default:
// operations to execute if the expression is not equal to any case
// ...
break;
}
The expression that switch
takes is not used directly as a logical expression. It is not evaluated as “if this condition is true,” because it would be in an if
statement. The value of the switch
expression is used in equality comparisons with the case
values. It is similar to an "if
, else if
, else
" chain that has only equality comparisons:
auto value = expression;
if (value == value_1) {
// operations for value_1
// ...
} else if (value == value_2) {
// operations for value_2
// ...
}
// ... other 'else if's ...
} else {
// operations for other values
// ...
}
However, the "if
, else if
, else
" above is not an exact equivalent of the switch
statement. The reasons for this will be explained in the following sections.
If a case
value matches the value of the switch
expression, then the operations that are under the case
are executed. If no value matches, then the operations that are under the default
are executed.
The goto
statement #
The use of goto
is generally advised against in most programming languages. However, goto
is useful in switch
statements in some situations.
case
does not introduce a scope like the if
statement does. Once the operations within an if
or else
scope are finished, the evaluation of the entire if
statement is also finished. That does not happen with the case
sections; once a matching case
is found, the execution of the program jumps to that case
and executes the operations under it. When needed in rare situations, goto case
makes the program execution jump to the next case
:
Get hands-on with 1400+ tech skills courses.