Using the switch Statement in C++

The switch statement allows you to execute different parts of code based on the value of a variable or expression. It's an alternative to using multiple if...else if statements when dealing with multiple possible values.

Syntax of the switch Statement

switch (expression) {
    case value1:
        // Code to execute when expression == value1
        break;
    case value2:
        // Code to execute when expression == value2
        break;
    // ...
    default:
        // Code to execute when expression doesn't match any case
}

Example: Using the switch Statement

#include <iostream>

int main() {
    int day;
    std::cout << "Enter a number (1-7) for the day of the week: ";
    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 day number." << std::endl;
    }
    
    return 0;
}

Key Takeaways

  • The switch statement simplifies code when checking a variable against multiple constant values.
  • The break statement prevents fall-through to the next case.
  • The default case handles any values not matched by the cases.

When to Use switch vs. if...else

  • Use switch when comparing a single variable to multiple constant values.
  • Use if...else for complex conditions or ranges.
  • switch statements can be more efficient and readable for certain scenarios.

Limitations of the switch Statement

  • The expression must evaluate to an integral or enumeration type.
  • Cannot use ranges or relational operators directly in cases.
  • Case labels must be constant expressions.