Lecture 11: Switch Statements
Monday, March 05, 2012[Up] [Previous Lecture] [Next Lecture]
Reading Assigned: 4.4 - 4.8
Homework Due: None
Homework Assigned: Homework 05 -- Assigned last class
Classwork Assigned: Classwork 07 -- delayed till next class
Topics Covered:
- Note on homework 5 getting character input
- Homework 5 questions
- Questions on quiz
- Switch
- A different syntax that performs a similar function to if-else-if-else logic
- Allows us to select from amongst multiple options given one input
- Example code using switch
- Note that the input and choices all must be integral values (int, char, etc.), so we cannot use switch with doubles
- Note that it cannot operate on ranges of items, all options must be discrete choices
- Break is used to indicate where the code should break out of the switch block of code
- COMMON MISTAKE: Forgetting a break at the end of a case statement
- A second example showing case statement fall through
- Case statement fall-through can be useful in some cases though, when multiple inputs must perform the same (or largely similar) functionality
- Example showing useful fall through