switch Statement Details

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 cases in our switch explicitly test for the lowercase and uppercase versions of the letters A, B, C, D and F. Note the cases in lines 62–63 that test for the values 'A' and 'a' (both of which represent the grade A). Listing cases consecutively with no statements between them enables the cases 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 cases execute until a break statement or the end of the switch is encountered.


Image Common Programming Error 5.5

Forgetting a break statement when one is needed in a switch statement is a logic error.



Image 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.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.108.197