THE SELECTIVE
STRUCTURE: SWITCH
Ø
A switch statement is a type of
selection control mechanism used to allow the value of a variable or
expression to change the control flow of program execution via
a multi-way branch.
Ø
The switch statement body consists of
a series of case labels, an optional default label
and breaks:
a. Case Statement
-
the case statement
is the one which compares several possible constant values for an expression
b. Default Statement
-
the default statement
is executed when no case statement satisfies the inputted value or the value
being switched
c. Break
-
break makes
the program jumps to the end of the switch selective structure once one of the
case statements have been satisfied
Ø
How it works:
Switch evaluates expression and checks
if it is equivalent to constant1, if it is, it executes a
group of
statements 1 until it finds the break statement. When it finds this break statement the program jumps to the end of the switch selective structure.
If expression was not equal to constant1 it will be checked against constant2. If it is
equal to this, it will execute group of statements 2 until
a break keyword is found, and then will jump to the end of the switch selective structure.
Finally, if the value of expression did not match any of the previously specified constants
(you can include as many case labels as values you want to
check), the program will execute the statements included after the default label, if it exists (since it is optional).
Ø
Things to remember when using Switch
·
It differs from the if statement in that
switch can only test for equality whereas the if conditional expression
can be of any type
·
No two case constants in the same switch can
have identical values
·
A switch statement is more efficient than the
if-else ladder