C++ Switch-Case Statement

The switch-case statement in C++ allows you to execute one block of code out of many options based on the value of an expression. It is often used as an alternative to long if-else if ladders.

1. Basic Switch-Case Example

The switch statement evaluates an expression and executes the matching case block. Use break to prevent fall-through.

C++
Example: Basic switch-case statement
#include <iostream>
using namespace std;

int main() {
    int day = 3;

    switch(day) {
        case 1:
            cout << "Monday" << endl;
            break;
        case 2:
            cout << "Tuesday" << endl;
            break;
        case 3:
            cout << "Wednesday" << endl;
            break;
        default:
            cout << "Invalid day" << endl;
    }

    return 0;
}

2. Common Mistakes

Always include break statements to prevent fall-through unless intentional. The default case is optional but recommended for handling unexpected values.

C++
Example: Missing break leads to fall-through
#include <iostream>
using namespace std;

int main() {
    int day = 2;

    switch(day) {
        case 1:
            cout << "Monday" << endl;
        case 2:
            cout << "Tuesday" << endl; // Both cases will run due to missing break
        case 3:
            cout << "Wednesday" << endl;
    }

    return 0;
}

Conclusion

Switch-case statements simplify multiple conditional checks in C++. Proper use of break and default ensures predictable program flow.