switch


Keyword: switch Statement

The switch statement in C++ is a control flow construct used for multi-way branching. It provides an efficient way to execute different code blocks based on the value of a single expression, often serving as an alternative to multiple if-else statements.

Key Characteristics

Example 1: Basic Usage: Day of the Week

#include <iostream>

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

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

    std::cout << std::endl;
    return 0;
}

Explanation:

2. Fall-through Behavior

#include <iostream>

int main() {
    char grade;
    std::cout << "Enter your grade (A, B, C, D, or F): ";
    std::cin >> grade;

    switch (grade) {
        case 'A':
        case 'B':
        case 'C':
            std::cout << "You passed!";
            break;
        case 'D':
            std::cout << "You barely passed.";
            break;
        case 'F':
            std::cout << "You failed.";
            break;
        default:
            std::cout << "Invalid grade entered.";
    }

    std::cout << std::endl;
    return 0;
}

Explanation:

3. Enum Class with Switch

#include <iostream>

enum class Color { Red, Green, Blue, Yellow };

int main() {
    Color selectedColor = Color::Blue;

    switch (selectedColor) {
        case Color::Red:
            std::cout << "You selected Red";
            break;
        case Color::Green:
            std::cout << "You selected Green";
            break;
        case Color::Blue:
            std::cout << "You selected Blue";
            break;
        case Color::Yellow:
            std::cout << "You selected Yellow";
            break;
    }

    std::cout << std::endl;
    return 0;
}

Explanation:

Example 4: Switch with Initialization (C++17)

#include <iostream>
#include <string>

int main() {
    std::cout << "Enter a fruit name: ";
    std::string fruit;
    std::cin >> fruit;

    switch (int length = fruit.length(); length) {
        case 5:
            std::cout << "The fruit name has 5 letters. Is it 'Apple'?";
            break;
        case 6:
            std::cout << "The fruit name has 6 letters. Is it 'Orange'?";
            break;
        case 7:
            std::cout << "The fruit name has 7 letters. Is it 'Banana'?";
            break;
        default:
            std::cout << "The fruit name has " << length << " letters.";
    }

    std::cout << std::endl;
    return 0;
}

Explanation:

Additional Considerations

  1. Performance: switch can be more efficient than multiple if-else statements, especially for a large number of cases.

  2. Compile-time Constants: Case labels must be compile-time constants, not variables.

  3. Default Case: It's a good practice to include a default case to handle unexpected values.

  4. Scoping: Each case in a switch statement does not create a new scope. Use blocks {} if you need to declare variables within a case.

Summary

The switch statement in C++ is a powerful control flow construct for multi-way branching based on a single expression. It offers a clean and efficient alternative to multiple if-else statements, especially when dealing with discrete values like integers or enumerations. Key features include the ability to handle multiple cases, intentional fall-through behavior, and a default case for unmatched values. While switch statements are limited to integral types and enumerations, they provide better readability and potentially better performance for multiple condition checking. Modern C++ (C++17 and later) has enhanced the switch statement with initialization capabilities, further improving its utility. When using switch, it's important to remember to use break statements to prevent unintended fall-through, consider all possible cases including a default, and be aware of the compile-time constant requirement for case labels.

Previous Page | Course Schedule | Course Content