Understanding the Switch Statement in C++

  • Last updated Apr 25, 2024

In C++, the switch statement is a control flow statement that provides a way to select one block of code from several alternatives based on the value of an expression. It is often used for situations where you have a single variable or expression that can take on different values, and you want to execute different code blocks depending on those values.

Here is the basic structure of a switch statement in C++:

switch (expression) {
    case value1:
        // Code to be executed if expression equals value1
        break;
    case value2:
        // Code to be executed if expression equals value2
        break;
    // Additional case statements for other values
    default:
        // Code to be executed if none of the cases match
}

The expression is evaluated, and the program flow will transfer to the code block corresponding to the value that matches the expression. Each case label represents a specific value that the expression can take on. The break statement is used to exit the switch statement after executing the corresponding code block. If none of the case values match the expression, the code block under the default label (if present) will be executed.

Here's an example of how a switch statement is used in C++:

#include <iostream>

int main() {
    int month;

    std::cout << "Enter a month (1-12): ";
    std::cin >> month;

    switch (month) {
        case 1:
            std::cout << "January" << std::endl;
            break;
        case 2:
            std::cout << "February" << std::endl;
            break;
        case 3:
            std::cout << "March" << std::endl;
            break;
        case 4:
            std::cout << "April" << std::endl;
            break;
        case 5:
            std::cout << "May" << std::endl;
            break;
        case 6:
            std::cout << "June" << std::endl;
            break;
        case 7:
            std::cout << "July" << std::endl;
            break;
        case 8:
            std::cout << "August" << std::endl;
            break;
        case 9:
            std::cout << "September" << std::endl;
            break;
        case 10:
            std::cout << "October" << std::endl;
            break;
        case 11:
            std::cout << "November" << std::endl;
            break;
        case 12:
            std::cout << "December" << std::endl;
            break;
        default:
            std::cout << "Invalid month" << std::endl;
    }

    return 0;
}

In this program, the user is prompted to enter a numeric value representing a month (1 for January, 2 for February, and so on). The switch statement then matches the input value with the corresponding case label and displays the name of the month. If the input doesn't match any of the cases (i.e., it's not in the range 1-12), the default case is executed, which prints Invalid month.