|
|
|
|
|
|
|
expression is any legal C++ expression, and the statements are any legal C++ statements or block of statements. switch evaluates expression and compares the result to each of the case values. Note, however, that the evaluation is only for equality; relational operators cannot be used here, nor can Boolean operations. |
|
|
|
|
|
|
|
|
If one of the case values matches the expression, execution jumps to those statements and continues to the end of the switch block unless a break statement is encountered. If nothing matches, execution branches to the optional default statement. If there is no default and no matching value, execution falls through the switch statement and the statement ends. |
|
|
|
|
|
|
|
|
It is almost always a good idea to have a default case in switch statements. If you have no other need for the default, use it to test for the supposedly impossible case and print out an error message; this can be a tremendous aid in debugging. |
|
|
|
|
|
|
|
|
|
It is important to note that if there is no break statement at the end of a case statement, execution will fall through to the next case. This is sometimes necessary, but usually is an error. If you decide to let execution fall through, be sure to put a comment indicating that you didn't just forget the break. |
|
|
|
|
|
|
|
|
Listing 8.15 illustrates the use of the switch statement. |
|
|
|
|
|
|
|
|
LISTING 8.15 DEMONSTRATING THEswitch STATEMENT |
|
|
|
 |
|
|
|
|
1: //Listing 8.15
2: // Demonstrates switch statement 3:
4: #include <iostream.h>
5:
6: int main()
7: {
8: unsigned short int number;
9: cout < Enter a number between 1 and 5: ;
10: cin >> number;
11: switch (number)
12: {
13: case 0: cout < Too small, sorry!;
14: break;
15: case 5: cout < Good job!\n; // fall through
16: case 4: cout < Nice Pick!\n; // fall through
17: case 3: cout < Excellent!\n; // fall through
18: case 2: cout < Masterful!\n; // fall through |
|
|
|
 |
|
|
|
|
continues |
|
|
|
|
|