The switch-case statement is a control statement used to execute one block of code from multiple options based on the value of a variable or an expression. It provides an alternative to using multiple if-else statements and can make the code cleaner and more readable when dealing with multiple conditions.
Here is the basic syntax of a switch-case statement in C++:
switch (expression) {
case constant1:
// code to be executed if expression == constant1
break;
case constant2:
// code to be executed if expression == constant2
break;
// you can have any number of case statements
default:
// code to be executed if expression doesn't match any constant
}
switch statement evaluates an expression once and compares the result with the values of each case label.case label must be a unique constant expression, typically integers or characters.break statement is used to exit from the switch block. If break is omitted, the execution will continue to the next case label (fall-through behavior).default case is optional but recommended. It executes if none of the case labels match the expression. Think of it as a final else in an if-else chain.break at the end of a case, the execution will continue to the next case. This can be useful in some situations but should be used with caution.#include <iostream>
int main() {
int day = 3;
switch (day) {
case 1:
std::cout << "Monday\n";
break;
case 2:
std::cout << "Tuesday\n";
break;
case 3:
std::cout << "Wednesday\n";
break;
case 4:
std::cout << "Thursday\n";
break;
case 5:
std::cout << "Friday\n";
break;
case 6:
std::cout << "Saturday\n";
break;
case 7:
std::cout << "Sunday\n";
break;
default:
std::cout << "Invalid day\n";
break;
}
return 0;
}
day is evaluated once.day is compared with each case label.day is 3, the code under case 3: is executed, printing “Wednesday”.break statement prevents the execution from falling through to case 4: and beyond.day had a value other than 1 to 7, the default case would be executed, printing “Invalid day”.case labels must be constants known at compile time.