Core Module
12 min forge
C++ Switch Statement
An efficient alternative to multiple if-else statements for multi-way branching.
C++ Switch Statement
π What is it
The switch statement executes one block of code from multiple options based on the value of an expression. It's often cleaner and more efficient than long if-else if chains.
β‘ When to use
Use switch when you have a single variable (integral or char) and multiple discrete values to check against.
π§ Time complexity
- Check: $O(1)$ (often implemented via a jump table by the compiler).
π» Code example
cpp Standardint day = 4; switch (day) { case 1: std::cout << "Monday"; break; case 4: std::cout << "Thursday"; break; default: std::cout << "Invalid day"; }
β Common mistakes
- Forgetting the
breakstatement, leading to "fall-through" where subsequent cases are executed. - Using
switchwith non-integral types likefloatorstring(C++ only supportsint,char, andenumsin switch). - Forgetting the
defaultcase to handle unexpected inputs.