switch
A switch statement selects from
among pieces of code based on the value of an integral expression. Its form
is:
switch(selector) {
case integral-value1 : statement; break;
case integral-value2 : statement; break;
case integral-value3 : statement; break;
case integral-value4 : statement; break;
case integral-value5 : statement; break;
(...)
default: statement;
}
Selector is an expression that
produces an integral value. The switch compares the result of
selector to each integral value. If it finds a match, the
corresponding statement (simple or compound) executes. If no match occurs, the
default statement
executes.
You will notice in the definition above
that each case ends with a
break, which causes execution to jump to the end of the switch
body (the closing brace that completes the switch). This is the
conventional way to build a switch statement, but the break is
optional. If it is missing, your case “drops through” to the
one after it. That is, the code for the following case statements execute
until a break is encountered. Although you don’t usually want this
kind of behavior, it can be useful to an experienced
programmer.
The switch statement is a clean
way to implement multi-way
selection (i.e., selecting from among a number of different execution paths),
but it requires a selector that evaluates to an integral value at compile-time.
If you want to use, for example, a string object as a selector, it
won’t work in a switch statement. For a string selector, you
must instead use a series of if statements and compare the string
inside the conditional.
The menu example shown above provides a
particularly nice example of a switch:
//: C03:Menu2.cpp
// A menu using a switch statement
#include <iostream>
using namespace std;
int main() {
bool quit = false; // Flag for quitting
while(quit == false) {
cout << "Select a, b, c or q to quit: ";
char response;
cin >> response;
switch(response) {
case 'a' : cout << "you chose 'a'" << endl;
break;
case 'b' : cout << "you chose 'b'" << endl;
break;
case 'c' : cout << "you chose 'c'" << endl;
break;
case 'q' : cout << "quitting menu" << endl;
quit = true;
break;
default : cout << "Please use a,b,c or q!"
<< endl;
}
}
} ///:~
The quit flag is a
bool, short for
“Boolean,” which is a type you’ll find only in C++. It can
have only the keyword values true or false. Selecting
‘q’ sets the quit flag to true. The next time the
selector is evaluated, quit == false returns false so the body of
the while does not
execute.