C++ Switch

The C++ programming language provides several control structures that allow developers to make decisions and execute specific blocks of code based on certain conditions. One such control structure is the switch statement, which provides a convenient way to handle multiple possible values for a single variable.

The switch statement in C++ is a powerful tool that allows you to compare the value of a variable against a set of predefined values, known as case labels. Based on the value of the variable, the switch statement will execute the corresponding block of code associated with the matching case label.

Here’s a simple example to illustrate how the switch statement works:


#include <iostream>

int main() {
    int day;
    std::cout << "Enter a number between 1 and 7: ";
    std::cin >> day;

    switch (day) {
        case 1:
            std::cout << "Sunday" << std::endl;
            break;
        case 2:
            std::cout << "Monday" << std::endl;
            break;
        case 3:
            std::cout << "Tuesday" << std::endl;
            break;
        case 4:
            std::cout << "Wednesday" << std::endl;
            break;
        case 5:
            std::cout << "Thursday" << std::endl;
            break;
        case 6:
            std::cout << "Friday" << std::endl;
            break;
        case 7:
            std::cout << "Saturday" << std::endl;
            break;
        default:
            std::cout << "Invalid input" << std::endl;
            break;
    }

    return 0;
}

In this example, we prompt the user to enter a number between 1 and 7. The input value is stored in the variable ‘day’. The switch statement then compares the value of ‘day’ against the case labels defined within the switch block.

If the value of ‘day’ matches one of the case labels, the corresponding block of code is executed. For example, if the user enters 3, the output will be “Tuesday”.

If none of the case labels match the value of ‘day’, the code within the ‘default’ case is executed. In this example, if the user enters a value other than 1 to 7, the output will be “Invalid input”.

It’s important to note that each case block should end with a ‘break’ statement. This is necessary to prevent the execution from falling through to the next case block. Without the ‘break’ statement, all subsequent case blocks would be executed regardless of whether their condition is met.

The switch statement in C++ can also be used with other data types such as characters and enumerated types. Additionally, multiple case labels can be associated with the same block of code, allowing for more flexibility in handling different values.

Overall, the switch statement is a valuable tool in C++ that simplifies decision-making and allows for efficient handling of multiple possible values for a variable. It provides a clear and concise way to structure code based on different conditions, making it easier to read and maintain.

Scroll to Top