Next: Examples of switch statements
Up: Introduction to C++ Programming
Previous: Exercises
In the last Lesson it was shown how a choice could
be made from more than two possibilities by using nested
if-else statements. However a less unwieldy method in some
cases is to use a switch statement. For example the following
switch statement will set the variable grade to the
character A, B or C depending on whether the variable i has the
value 1, 2, or 3. If i has none of the values 1, 2, or 3 then
a warning message is output.
switch (i)
{
case 1 : grade = 'A';
break;
case 2 : grade = 'B';
break;
case 3 : grade = 'c';
break;
default : cout << i
<< " not in range";
break;
}
The general form of a switch statement is:
switch ( selector
{
case label1: statement1;
break;
case label2: statement2;
break;
...
case labeln: statementn;
break;
default: statementd; // optional
break;
}
The selector may be an integer or character
variable or an expression that evaluates to an integer or a character.
The selector is evaluated and the value compared with each of the
case labels. The case labels must have the
same type as the selector and they must all be different.
If a match is found between the selector and one of the case labels, say
labeli , then the statements from the statement
statementi until the next break statement will be
executed. If the value of the selector cannot be matched with any of
the case labels then the statement associated with default is
executed. The default is optional but it should only be left
out if it is certain that the selector will always take the value of
one of the case labels. Note that the statement associated with a
case label can be a single statement or a sequence of statements
(without being enclosed in curly brackets).