Switch-Case Statements in C++ tutorial
Switch-Case Statements in cplus
Switch-case statements are used to execute one block of code among many options based on the value of an expression. They are a cleaner alternative to long if-else if chains when testing a single variable against multiple values.
switch (expression) {
case constant1:
// Code block for constant1
break;
case constant2:
// Code block for constant2
break;
...
default:
// Code block if no case matches
}
Key Points:
The expression must evaluate to an integer or character type.
case labels must be unique constant values.
The break statement prevents fall-through to the next case.
The default block is optional but useful for handling unexpected values.
#include <iostream>
using namespace std;
int main() {
int day = 3;
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;
default:
cout << "Weekend" << endl;
}
return 0;
}
Output:
Wednesday
You can place one switch inside another if needed.
int x = 1, y = 2;
switch (x) {
case 1:
switch (y) {
case 2:
cout << "x=1 and y=2";
break;
}
break;
}
Always include a default case to handle unexpected values.
Use break to prevent fall-through unless fall-through behavior is intended.
Keep switch statements readable and avoid deeply nested structures.