C++ Switch

In C++, the switch statement provides a way to conditionally execute different blocks of code based on the value of an expression. It allows for multiple branches of execution depending on the value of a variable or expression. The switch statement is commonly used when you have a limited number of possible values to check against. The syntax for the switch statement in C++ is as follows:

Example
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 valueN:
        // Code to be executed if expression matches valueN
        break;
    default:
        // Code to be executed if expression does not match any of the values
        break;
}

Here's a breakdown of the components:

  • expression: An expression that is evaluated to determine which case to execute. It can be an integer, character, enumeration, or a few other data types.

  • case: Each case label represents a possible value that the expression might match. If the expression matches a particular case value, the corresponding block of code is executed.

  • break: The break statement is used to exit the switch statement after a matching case block is executed. It prevents the flow of execution from falling through to the next case. If break is omitted, the execution continues to the next case and subsequent code blocks, regardless of whether their conditions match.

  • default: The default case is optional and represents the block of code that is executed when none of the case values match the expression.

Example
int choice = 2;

    switch (choice) {
        case 1:
            cout << "You selected option 1." << endl;
            break;
        case 2:
            cout << "You selected option 2." << endl;
            break;
        case 3:
            cout << "You selected option 3." << endl;
            break;
        default:
            cout << "Invalid option." << endl;
            break;
    }
    

In this example, the value of the choice variable is evaluated against each case value. If choice is 1, the code block under case 1 will be executed. If choice is 2, the code block under case 2 will be executed, and so on. If none of the case values match, the code block under default will be executed.

It's important to note that the expression used in the switch statement must result in an integral or enumeration type. The switch statement provides an alternative approach to using multiple if-else statements when you have a limited number of possibilities to consider.