C++ - Switch
Overview
Estimated time: 20–30 minutes
Branch on integral or enum values using switch/case/default. Learn when fallthrough occurs and how to avoid it.
Learning Objectives
- Write switch statements with case and default labels.
- Prevent unintended fallthrough with break.
Prerequisites
Example
int day=2;
switch(day){
case 1: /*...*/ break;
case 2: /*...*/ break;
default: /*...*/ break;
}
Common Pitfalls
- Forgetting break causes fallthrough.