The switch statement in C++ is used to select one of many code blocks to be executed based on the value of an expression. It’s typically used when you need to compare a variable against multiple possible values, making your code cleaner and more readable than using multiple if-else statements.
Syntax:
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
// additional cases as needed
default:
// code to be executed if expression doesn't match any case
}
Explanation:
- expression: This is the value or variable that you want to test.
- case value: Each case represents a potential match. If the expression matches the value, the corresponding block of code is executed.
- break: After executing a case, the break statement is used to exit the switch block. If you omit the break, the code will “fall through” to the next case.
- default: This is an optional block that executes if none of the case values match the expression.
Example:
#include <iostream>
using namespace std;
int main() {
int day = 2;
switch (day)
{
case 1:
cout << "Monday"<< endl;
break;
case 2:
cout << "Tuesday"<< endl;
break;
case 3:
cout << "Wednesday"<< endl;
break;
default:
cout << "Invalid day"<< endl;
break;
}
return 0;
}
Output:
Tuesday
Example:
#include <iostream>
using namespace std;
enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
int main() {
Day today = Friday; // No need for 'Day.' here
switch (today) {
case Monday:
cout << "Start of the work week!" << endl;
break;
case Friday:
cout << "End of the work week!" << endl;
break;
default:
cout << "It's a regular day." << endl;
break;
}
return 0;
}
Output:
End of the work week!