The Switch Statement
- This is from chapter 7, section 1
- It is a continuation of selection, so I will cover it here.
- This is ONLY for enumerable types
- A type is enumerable if each potential value has a known predecessor and successor.
- Integer types qualify
- enum (which is the first thing in 230) qualifies
- Strings, floats, and most other data types do not qualify.
- Syntax is somewhat complex
- switch (enumerable expression) { }
- Inside the code block is a series of case statements
- case value: [statements;] (the statement is optional)
- or default: statements;
- The case values must be constants.
- A syntax error is generated if two cases are identical.
- Semantics
- Evaluate the enumerable expression
- Find the corresponding case and execute through the end of the code block
- If no corresponding case exists, and the default case does, execute statements starting with default.
- This is really not the desired behavior, so we use the break statement.
- The break statement exits the innermost control structure.
- You may only use the break statement in switch statements for your stay here at Edinboro.
- DO NOT USE BREAK TO EXIT
- if, if-else
- loops of any type
- A switch example:
- Write a simple adventure game. The user is in a field, to the north is a nasty bear, to the east a lion, to the south an alligator and to the west a nice sunset and a happy ending. Ask the user for a single character, the direction they wish to travel. Accept the following
Key | Direction |
N, w, k | North |
S, s, j | South |
E, a, h | East |
W, d, l | West |
- A simple implementation
- How will I test this code?
- I will play all 12 letters to make sure that they work.
- I will try some other characters as well.
- Should you use the switch statement
- I believe you should for several reasons
- It is easier to modify than if - else if - else ...
- It checks for duplicate case, thus preventing errors.