Switch Statement
C++ Switch Statement
Definition: The switch statement is a multi-way branch statement. It provides an efficient way to transfer execution to different parts of code based on the value of a single expression. It is often used as a cleaner, more readable alternative to long if-else if ladders when you are comparing one variable against multiple fixed values.
Why: The switch statement is a staple of beginner C++ curricula because it teaches structured decision-making. It is particularly useful for handling menu selections, keyboard inputs, or any scenario where a variable can have a specific set of known constants.
Syntax and Structure
The switch expression is evaluated once. The value of the expression is then compared with the values of each case. If there is a match, the associated block of code is executed.
Example: Day of the Week
In this example, the program uses the value of the day variable to determine which string to print to the console:
#include <iostream> using namespace std; int main() { int day = 2; switch(day) { case 1: cout << "Monday"; break; case 2: cout << "Tuesday"; break; default: cout << "Invalid"; } return 0; }
Key Components of a Switch Block
| Keyword | Purpose |
|---|---|
switch |
Specifies the variable or expression to be tested. |
case |
Defines a possible value for the variable. If it matches, the code follows until a break is hit. |
break |
Crucial! It "breaks" out of the switch block. Without it, the program will continue executing the next cases automatically (this is called "fall-through"). |
default |
Optional. It specifies code to run if no case matches. Think of it as the final "else" in an if-else ladder. |
Key Notes
- Integral Types Only: In C++, the switch expression must result in an
int,char, orenum. You cannot switch on astringor afloat. - Constant Cases: The value following the
casekeyword must be a constant or a literal (e.g.,'A'or5). You cannot use a variable in a case label. - Efficiency: For a large number of cases, a
switchis often faster than anif-elseladder because the compiler can use a "jump table" to find the correct branch immediately. - Intentional Fall-through: Sometimes developers omit the
breakon purpose so that multiple cases execute the same block of code. However, for beginners, it is safest to always end each case with abreak.
🏋️ Test Yourself With Exercises
Take our quiz on Switch Statement to test your knowledge.
Browse Quizzes »