C++ Demystified(c) A Self-Teaching Guide
The switch statement is similar to an if /else if /else statement. It evaluates the value of an integer expression and then compares that value to two or more other values to determine which code to execute.
The following program shows a switch statement in action in a program that determines your average based on your grade:
#include <iostream> using namespace std; int main(void) { char grade; cout << "Enter your grade: "; cin >> grade; switch (grade) { case 'A': cout << "Your average must be between 90 - 100" << endl; break; case 'B': cout << "Your average must be between 80 - 89" << endl; break; case 'C': cout << "Your average must be between 70 - 79" << endl; break; case 'D': cout << "Your average must be between 60 - 69" << endl; break; default: cout << "Your average must be below 60" << endl; } return 0; }
Here are several sample runs, each separated by a dotted line:
Enter your grade: C Your average must be between 70 - 79 ------ Enter your grade: A Your average must be between 90 - 100 ------ Enter your grade: F Your average must be below 60
Figure 5-6 uses a flowchart to illustrate this program.
Let s now analyze the program.
The switch keyword evaluates an integer expression, grade . While grade is a character variable, every character has a corresponding integer value.
Earlier in this chapter, we discussed flowchart symbols prescribed by the American National Standard Institute (ANSI), and mentioned that ANSI also prescribes other standards that we will be using in this book. One of those other standards is the ANSI character set, which includes 256 characters , each having an integer value between 0 and 255. These values also are called ASCII values, since values 0 to 127 of the ANSI character set are the same as in the ASCII (American Standard Code for Information Interchange) character set.
Table 5-4 lists the ANSI/ASCII values for commonly used characters. Note that digits also can be characters, and that the ANSI/ASCII value of an uppercase character is different than the value of the corresponding lowercase character.
Character | Value |
---|---|
| 48 |
9 | 57 |
A | 65 |
Z | 90 |
a | 97 |
z | 122 |
Each case keyword is followed by an integer expression that must be constant, that is, it cannot change in value during the life of the program. Therefore, a variable cannot follow a case keyword. In this program, the constant is a character literal, such as A, B, and so on. Each character s ANSI value is an integer value, and the integer expression is followed by a colon .
Caution | A common mistake is to follow the integer expression not with a colon but with a semicolon, which is typically used to terminate statements. This will cause a compiler error. |
The default keyword serves the same purpose as an else part in an if /else if /else statement, and therefore is not followed by an integer expression.
The integer expression following the switch keyword is evaluated and compared with the integer constant following each case keyword, from top to bottom. If there is a match ” that is, the two integers are equal ”then the statements belonging to that case are executed. Otherwise, they are not. Thus, the statements belonging to a case are conditional, just as are statements in an if, else if, or else part. However, unlike an if /else if /else statement, multiple conditional statements belonging to a case do not need to be enclosed in curly braces.
Differences Between switch and if /else if /else Statements
While a switch statement is similar to an if /else if /else statement, there are important differences.
One difference is that in an if /else if /else statement, the comparison following the if part may be independent of the comparison following an else if part. The following example, while perhaps a bit silly, is illustrative of this concept:
if (apples == oranges) do this; else if (sales >= 5000) do that;
By contrast, in a switch statement, the constant integer expression following a case keyword must be compared with the value following the switch keyword, and nothing else. The next chapter on logical operators discusses other differences between switch and if /else if /else statements. However, two differences can be discussed now. One is commonly known as falling through. The other concerns ranges of numbers .
Falling Through
In an if /else if /else statement, each part is separate from all the others. By contrast, in a switch statement (once a matching case statement is found), unless a break statement is reached, execution falls through to the following case statements that execute their conditional statements without checking for a match. For example, if you removed the break statements from the program, you could have the following sample run:
Enter your grade: A Your average must be between 90 100 Your average must be between 80 - 89 Your average must be between 70 - 79 Your average must be between 60 - 69 Your average must be below 60
This falling through behavior is not necessarily bad. In the following modification of the grade program, the falling-through behavior permits the user to enter a lowercase grade in addition to an uppercase grade.
#include <iostream> using namespace std; int main(void) { char grade; cout << "Enter your grade: "; cin >> grade; switch (grade) { case 'a': case 'A': cout << "Your average must be between 90 - 100" << endl; break; case 'b': case 'B': cout << "Your average must be between 80 - 89" << endl; break; case 'c': case 'C': cout << "Your average must be between 70 - 79" << endl; break; case 'd': case 'D': cout << "Your average must be between 60 - 69" << endl; break; default: cout << "Your average must be below 60" << endl; } return 0; }
Another example occurs in the following program. Since the D (for deluxe) option includes the feature in the L (for leather) option, case ˜D deliberately falls through the case ˜L.
#include <iostream> using namespace std; int main(void) { char choice; cout << "Choose your car\n"; cout << "S for Standard\n"; cout << "L for Leather Seats\n"; cout << "D for Leather Seats + Chrome Wheels\n"; cin >> choice; cout << "Extra features purchased\n"; switch (choice) { case 'D': cout << "Chrome wheels\n"; case 'L': cout << "Leather seats\n"; break; default: cout << "None selected\n";} return 0; }
The sample run could be
Choose your car S for Standard L for Leather Seats D for Leather Seats + Chrome Wheels D Extra features purchased Chrome wheels Leather seats
Ranges of Numbers
Another difference between switch and if/else ifelse statements concerns the handling of ranges of numbers. For example, earlier in this chapter we used an if /else if /else statement to output the user s grade based on the test score that was input by the user. The issued grade was an A if the test score was between 90 and 100, a B if the test score was between 80 and 89, and so on. The if /else if /else statement in that program was
if (testScore >= 90) cout << "Your grade is an A" << endl; else if (testScore >= 80) cout << "Your grade is a B" << endl; else if (testScore >= 70) cout << "Your grade is a C" << endl; else if (testScore >= 60) cout << "Your grade is a D" << endl; else cout << "Your grade is an F" << endl;
By contrast, a case statement cannot be followed by an expression such as testScore >= 90 because the case statement keyword has to be followed by an integer constant. Instead, a case statement would be necessary for each possible test score. The following code fragment shows only the code for an A or B grade to avoid the code example being unduly long, but the code for a C or D grade would be essentially a repeat (an F grade would be handled with the default keyword).
switch (testScore) { case 100: case 99: case 98: case 97: case 96: case 95: case 94: case 93: case 92: case 91: case 90: cout << "Your grade is an A"; break; case 89: case 88: case 87: case 86: case 85: case 84: case 83: case 82: case 81: case 80: cout << "Your grade is an A"; break; }
This code example illustrates that the switch statement is more cumbersome than the if /else if /else structure in dealing with ranges of numbers.
Категории