The switch statement
- The switch statement is for situations when you have multiple (typically
more than three) cases or outcomes you'd like your code to consider.
- Example: Suppose you are writing code to make your program do
different things based on a letter command which the user types (i.e., like
a hot key). If there are many different keys the user could type
(e.g., 's' to save a file, 'a' to save as ..., 'o' to open a file, 'c' to
close the file, 'y' to copy, 'p' to paste and 'x' to exit the program.) an
if - else if - else if ... statement would be cumbersome. The switch
statement is better.
- Syntax:
- switch (switch_variable) { case literal_1: statements case literal_2:
statements .... case literal_n: statements }
- Examples of the switch statement