The switch statement is a decision-making statement in C++ that allows a program to choose one option from multiple possible values. It is often used when a variable can take several discrete values.
Purpose: To simplify decision-making when there are many possible cases.
Advantage: Cleaner and more readable than using multiple
if-elsestatements.
Syntax of switch Statement
Explanation:
expression: A variable or value to evaluate. Must be integer, char, or enum type.case value:Each case is a possible value of the expression.break: Stops execution of the switch after the matching case executes.default: Optional; executes if no case matches.
Example 1: Simple Switch Statement
Output:
The
dayvariable equals3, so case 3 executes.Without
break, execution continues to the next case (fall-through behavior).
Example 2: Switch Statement with Characters
Output:
Switch works with characters as well as integers.
Using Default Case
The
defaultcase handles unexpected values.It is optional, but recommended for robust programs.
Output:
When to Use Switch vs If
| Feature | Switch | If / If-Else |
|---|---|---|
| Number of cases | Best for many discrete values | Can handle any number of conditions |
| Condition type | Works only with integer, char, enum | Works with any Boolean expression |
| Readability | Cleaner for many specific values | Can become long and complex with many else-if |
| Fall-through behavior | Yes, without break | No, each if executes independently |
| Flexibility | Limited to equality checks | More flexible, supports complex conditions |
Example: If vs Switch
If-Else Version:
Switch Version:
Both programs give the same output, but
switchis easier to read when there are many cases.
Example 3: Real-Life Scenario – Menu Selection
switchis ideal for menus, options, and discrete selections.
Key Points About Switch
Expression must be integer, char, or enum.
Use
breakto prevent fall-through.defaulthandles all unmatched cases.Cannot use ranges or complex conditions in
switch.