C++ switch Statement
π C++ switch Statement
switch statement ka use tab hota hai jab ek variable/expression ki value ke base par multiple choices mein se ek select karna ho.
Ye aksar menu-driven programs aur fixed options ke liye use hota hai.
πΉ 1. Syntax
π expression ka type usually int, char, enum hota hai.
πΉ 2. Basic Example
Output:
πΉ 3. Why break is Important?
Output:
π break na ho to fall-through hota hai.
β Correct:
πΉ 4. default Case
π Jab koi case match na kare, default run hota hai.
πΉ 5. Switch with char
πΉ 6. Multiple Cases for One Block
πΉ 7. Switch vs If-Else
switch |
if-else |
|---|---|
| Fixed values | Range & conditions |
| Cleaner for menus | More flexible |
| Faster (sometimes) | More readable for logic |
β Limitations of switch
-
Float/double allowed β
-
Relational operators (
> <) β -
Range checks β
β For these, use if-else.
π Summary
-
switch= multi-way decision -
breakavoids fall-through -
defaulthandles unmatched cases -
Best for menu & fixed options
