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 Standard
int 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 break statement, leading to "fall-through" where subsequent cases are executed.
  • Using switch with non-integral types like float or string (C++ only supports int, char, and enums in switch).
  • Forgetting the default case to handle unexpected inputs.