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

switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}

πŸ‘‰ expression ka type usually int, char, enum hota hai.


πŸ”Ή 2. Basic Example

int day = 3;

switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
default:
cout << "Invalid day";
}

Output:

Wednesday

πŸ”Ή 3. Why break is Important?

int x = 1;

switch (x) {
case 1:
cout << "One ";
case 2:
cout << "Two";
}

Output:

One Two

πŸ‘‰ break na ho to fall-through hota hai.

βœ” Correct:

case 1:
cout << "One";
break;

πŸ”Ή 4. default Case

switch (choice) {
case 1:
cout << "Start";
break;
default:
cout << "Invalid choice";
}

πŸ‘‰ Jab koi case match na kare, default run hota hai.


πŸ”Ή 5. Switch with char

char grade = 'B';

switch (grade) {
case 'A':
cout << "Excellent";
break;
case 'B':
cout << "Good";
break;
case 'C':
cout << "Average";
break;
default:
cout << "Fail";
}


πŸ”Ή 6. Multiple Cases for One Block

char ch = 'a';

switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
cout << "Vowel";
break;
default:
cout << "Consonant";
}


πŸ”Ή 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

  • break avoids fall-through

  • default handles unmatched cases

  • Best for menu & fixed options

You may also like...