🔀 C++ switch Statement – Clean Multi-Condition Handling
The switch statement is a neater way to handle multiple if-else conditions when you’re checking the same variable. It’s like a traffic controller directing the flow based on different cases! 🚦
🧠 Syntax of switch
switch (expression) {
case value1:
// Code for case value1
break;
case value2:
// Code for case value2
break;
...
default:
// Code if no case matches
}
Note: Each case should end with a break; to stop execution from falling through to the next case.
🔧 Example: switch Statement in Action
#include <iostream>
using namespace std;
int main() {
int day;
cout << "Enter a number (1-7): ";
cin >> day;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
case 4:
cout << "Thursday" << endl;
break;
case 5:
cout << "Friday" << endl;
break;
case 6:
cout << "Saturday" << endl;
break;
case 7:
cout << "Sunday" << endl;
break;
default:
cout << "Invalid day!" << endl;
}
return 0;
}
💡 When to Use switch?
- When you’re checking the same variable against multiple constant values.
- When if-else becomes too long and messy.
- When you want to make your code easier to read and manage.
Think of switch as a clean alternative to a jungle of if-else statements. 🌴✨