switch
Multiple-Selection StatementC++ provides the switch
multiple-selection statement to choose among many different actions based on the possible values of a variable or expression. Each action is associated with the value of an integral constant expression (i.e., any combination of character and integer constants that evaluates to a constant integer value).
switch
Statement to Count A, B, C, D and F GradesFigure 5.11 calculates the class average of a set of numeric grades entered by the user, and uses a switch
statement to determine whether each grade is the equivalent of an A, B, C, D or F and to increment the appropriate grade counter. The program also displays a summary of the number of students who received each grade.
The main
function (Fig. 5.11) declares local variables total
(line 8) and gradeCounter
(line 9) to keep track of the sum of the grades entered by the user and the number of grades entered, respectively. Lines 10–14 declare and initialize to 0 counter variables for each grade category. The main
function has two key parts. Lines 24–51 read an arbitrary number of integer grades from the user using sentinel-controlled iteration, update variables total
and gradeCounter
, and increment an appropriate letter-grade counter for each grade entered. Lines 54–73 output a report containing the total of all grades entered, the average grade and the number of students who received each letter grade.
Lines 16–19 prompt the user to enter integer grades or type the end-of-file indicator to terminate the input. The end-of-file indicator is a system-dependent keystroke combination used to indicate that there’s no more data to input. In Chapter 14, File Processing, you’ll see how the end-of-file indicator is used when a program reads its input from a file.
On UNIX/Linux/Mac OS X systems, end-of-file is entered by typing the sequence
<Ctrl> d
on a line by itself. This notation means to simultaneously press both the Ctrl key and the d key. On Windows systems, end-of-file can be entered by typing
<Ctrl> z
[Note: On some systems, you must press Enter after typing the end-of-file key sequence. Also, Windows typically displays the characters ^Z
on the screen when the end-of-file indicator is typed, as shown in the output of Fig. 5.11.]
The keystroke combinations for entering end-of-file are system dependent.
The while
statement (lines 24–51) obtains the user input. Line 24
while (cin >> grade) {
performs the input in the while
statement’s condition. In this case, the loop-continuation condition evaluates to true if cin
successfully reads an int
value. If the user enters the end-of-file indicator, the condition evaluates to false.
If the condition evaluates to true, line 25 adds grade
to total
and line 26 increments gradeCounter
. These variables are used to compute the average of the grades. Next, lines 29–50 use a switch
statement to increment the appropriate letter-grade counter based on the numeric grade entered.
The switch
statement (lines 29–50) determines which counter to increment. We assume that the user enters a valid grade in the range 0–100. A grade in the range 90–100 represents A, 80–89 represents B, 70–79 represents C, 60–69 represents D and 0–59 represents F. The switch
statement consists of a block that contains a sequence of case
labels and an optional default
case. These are used in this example to determine which counter to increment based on the grade.
When the flow of control reaches the switch
, the program evaluates the expression in the parentheses (grade / 10
) following keyword switch
. This is the switch
’s controlling expression. The program compares this expression’s value with each case
label. The expression must have a signed or unsigned integral type—bool
, char
, char16_t
, char32_t
, wchar_t
, int
, long
or long long
. The expression can also use the C++11 signer or unsigned integral types, such as int64_t
and uint64_t
—see the <cstdint>
header for a complete list of these type names.
The controlling expression in line 29 performs integer division, which truncates the fractional part of the result. When we divide a value from 0 to 100 by 10, the result is always a value from 0 to 10. We use several of these values in our case
labels. If the user enters the integer 85
, the controlling expression evaluates to 8. The switch
compares 8
with each case
label. If a match occurs (case 8:
at line 35), that case
’s statements execute. For 8
, line 36 increments bCount
, because a grade in the 80s is a B. The break
statement (line 37) causes program control to proceed with the first statement after the switch
—in this program, we reach the end of the while
loop, so control returns to the loop-continuation condition in line 24 to determine whether the loop should continue executing.
The case
s in our switch
explicitly test for the values 10
, 9
, 8
, 7
and 6
. Note the cases at lines 30–31 that test for the values 9
and 10
(both of which represent the grade A). Listing cases consecutively in this manner with no statements between them enables the cases to perform the same set of statements—when the controlling expression evaluates to 9
or 10
, the statements in lines 32–33 will execute. The switch
statement does not provide a mechanism for testing ranges of values, so every value you need to test must be listed in a separate case
label. Each case
can have multiple statements. The switch
statement differs from other control statements in that it does not require braces around multiple statements in a case
.
case
without a break
StatementWithout break
statements, each time a match occurs in the switch
, the statements for that case and subsequent cases execute until a break
statement or the end of the switch
is encountered. This is often referred to as “falling through” to the statements in subsequent case
s. (This feature is perfect for writing a concise program that displays the iterative song “The Twelve Days of Christmas” in Exercise 5.28.)
Forgetting a break
statement when one is needed in a switch
is a logic error.
default
CaseIf no match occurs between the controlling expression’s value and a case
label, the default
case (lines 47–49) executes. We use the default
case in this example to process all controlling-expression values that are less than 6
—that is, all failing grades. If no match occurs and the switch
does not contain a default
case, program control simply continues with the first statement after the switch
.
In a switch
, ensure that you test for all possible values of the controlling expression.
Lines 54–73 output a report based on the grades entered (as shown in the input/output window in Fig. 5.11). Line 60 determines whether the user entered at least one grade—this helps us avoid dividing by zero. If so, line 62 calculates the average of the grades. Lines 65–69 then output the total of all the grades, the class average and the number of students who received each letter grade. If no grades were entered, line 72 outputs an appropriate message. The output in Fig. 5.11 shows a sample grade report based on 10 grades.
switch
Statement UML Activity DiagramFigure 5.12 shows the UML activity diagram for the general switch
statement. Most switch
statements use a break
in each case
to terminate the switch
statement after processing the case
. Figure 5.12 emphasizes this by including break
statements in the activity diagram. The diagram makes it clear that the break
statement at the end of a case
causes control to exit the switch
statement immediately.
The break
statement is not required for the switch
’s last case
(or the optional default
case, when it appears last), because execution continues with the next statement after the switch
.
Provide a default
case in switch
statements. This focuses you on the need to process exceptional conditions.
Although each case
and the default
case in a switch
can occur in any order, place the default
case last. When the default
case is listed last, the break
for that case is not required.
case
of a switch
When using the switch
statement, remember that each case
must contain a constant integral expression—that is, any combination of integer constants that evaluates to a constant integer value (e.g., –7, 0 or 221). An integer constant is simply an integer value. In addition, you can use character constants—specific characters in single quotes, such as 'A'
, '7'
or '$'
—which represent the integer values of characters and enum
constants (introduced in Section 6.8). (Appendix B shows the integer values of the characters in the ASCII character set, which is a subset of the Unicode® character set.)
The expression in each case
also can be a constant variable—a variable containing a value which does not change for the entire program. Such a variable is declared with keyword const
(discussed in Chapter 6).
In Chapter 12, Object-Oriented Programming: Polymorphism, we present a more elegant way to implement switch
logic—we use a technique called polymorphism to create programs that are often clearer, easier to maintain and easier to extend than programs using switch
logic.