C++ Switch
Lesson outline
Introduction to Switch
The switch statement is a control structure used to test a variable against a list of constant values (cases).
It is a cleaner and often more efficient alternative to long if-else if chains when checking a single variable against multiple options.
Basic Syntax
Simple Example
The break Keyword
The break statement ends the current case. Without it, execution continues into the next case (fall-through).
Intentional Fall-Through
Sometimes fall-through is used intentionally when multiple cases share the same code. In C++17+, use the [[fallthrough]] attribute to document intent.
The default Case
The default case executes when no other case matches. It is optional but recommended for robustness.
Switch with Enums
Switch works well with enumerated types. With scoped enums (enum class), qualify enumerators with the enum type.
C++17 Initialization in Switch
C++17 allows an init-statement directly inside a switch header. The declared variable is scoped to the switch.
Real-World Example: Menu System
Switch statements are commonly used for menu-driven programs.
Limitations of Switch
- Only checks for equality (no ranges or complex conditions).
- Case values must be constant expressions.
- Cannot switch directly on strings (use if-else, maps, hashing, or map to an enum).
- Limited to integral and enumeration types (not floating point or class types).
Best Practices
- Use
breakunless fall-through is intentional. - Document intentional fall-through (prefer
[[fallthrough]]in C++17+). - Keep case blocks concise—extract complex logic into functions.
- Prefer switch over long if-else chains for constant equality checks.
- Use
enum classfor stronger type safety and qualified enumerators. - Ensure all case labels are unique; unreachable or duplicate labels are ill-formed.