C++ - Switch Case

In C++, the switch statement is used to perform different actions based on the value of a variable or an expression. It provides an alternative to multiple if...else if...else statements when you have a series of conditions to check. Here's the syntax of the switch statement:

switch (expression) {
    case value1:
        // Code to be executed if expression matches value1
        break;
    case value2:
        // Code to be executed if expression matches value2
        break;
    case value3:
        // Code to be executed if expression matches value3
        break;
    // ...
    default:
        // Code to be executed if expression does not match any case
}

The expression is evaluated, and its value is compared with the values specified in each case label. If a match is found, the corresponding code block is executed until a break statement is encountered or the end of the switch statement is reached.

int day = 2;
std::string dayName;
switch (day) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    // ...
    default:
        dayName = "Invalid day";
}
std::cout << "The day is: " << dayName << std::endl;

Another example with default result

char grade = 'B';
std::string result;
switch (grade) {
    case 'A':
    case 'B':
        result = "Good";
        break;
    case 'C':
        result = "Average";
        break;
    case 'D':
    case 'E':
        result = "Poor";
        break;
    default:
        result = "Invalid grade";
}
std::cout << "The result is: " << result << std::endl;

In the second example, notice the use of multiple case labels without break statements. This allows you to handle multiple cases with the same code block.

The default label is optional and specifies the code to be executed if the expression does not match any of the case labels.

It's important to include break statements after each case to exit the switch block. Otherwise, the execution will continue into the next case until a break statement is encountered or the end of the switch statement is reached. This behavior is known as "fall-through".

Switch statements are particularly useful when you have a fixed set of possible values or discrete ranges to check. They provide a more concise and structured approach compared to long chains of if...else if...else statements.