The switch
statement consists of a series of case labels and an optional default case. These are used in this example to determine which counter to increment, based on a grade. When the flow of control reaches the switch
, the program evaluates the expression in the parentheses (i.e., grade
) following keyword switch
(line 60). This is called the controlling expression. The switch
statement compares the value of the controlling expression with each case
label. Assume the user enters the letter C
as a grade. The program compares C
to each case
in the switch
. If a match occurs (case 'C':
in line 72), the program executes the statements for that case
. For the letter C
, line 74 increments cCount
by 1
. The break
statement (line 75) causes program control to proceed with the first statement after the switch
—in this program, control transfers to line 97. This line marks the end of the body of the while
loop that inputs grades (lines 57–97), so control flows to the while
’s condition (line 57) to determine whether the loop should continue executing.
The case
s in our switch
explicitly test for the lowercase and uppercase versions of the letters A, B, C, D and F. Note the case
s in lines 62–63 that test for the values 'A'
and 'a'
(both of which represent the grade A). Listing case
s consecutively with no statements between them enables the case
s to perform the same set of statements—when the controlling expression evaluates to either 'A'
or 'a'
, the statements in lines 64–65 will execute. Each case
can have multiple statements. The switch
selection statement does not require braces around multiple statements in each case
.
Without break
statements, each time a match occurs in the switch
, the statements for that case
and subsequent case
s execute until a break
statement or the end of the switch
is encountered.
Common Programming Error 5.5
Forgetting a break statement when one is needed in a switch statement is a logic error.
Common Programming Error 5.6
Omitting the space between the word case and the integral value tested in a switch statement—e.g., writing case3: instead of case 3:—is a logic error. The switch statement will not perform the appropriate actions when the controlling expression has a value of 3.