Lesson 27 of 60 – switch Statement in C++
45%

switch Statement in C++

The switch statement is used when a program needs to choose one block of code from multiple possible choices based on the value of an expression.

Note: A switch statement is especially useful when one value needs to be compared with several fixed values, such as menu choices, day numbers, or month numbers.

1. What is a switch Statement?

The switch statement provides another way to perform multi-way decision making in C++.

switch (expression) {

    case value1:
        // statements
        break;

    case value2:
        // statements
        break;

    default:
        // statements
}

2. Why Use switch?

A switch statement can make code easier to read when the same expression needs to be compared against several fixed values.

For example:

  • 1 → Monday
  • 2 → Tuesday
  • 3 → Wednesday
  • 4 → Thursday
  • 5 → Friday

A switch statement can handle these choices clearly.

3. Basic switch Syntax

switch (expression) {

    case value1:
        statement;
        break;

    case value2:
        statement;
        break;

    default:
        statement;
}

The expression is evaluated and compared with the values specified in the case labels.

4. The case Keyword

The case keyword defines a possible value for the switch expression.

int choice = 2;

switch (choice) {

    case 1:
        std::cout << "Option 1";
        break;

    case 2:
        std::cout << "Option 2";
        break;
}

Since the value of choice is 2, the second case executes.

5. The break Statement

The break statement stops the switch statement after a matching case has executed.

int number = 1;

switch (number) {

    case 1:
        std::cout << "One";
        break;

    case 2:
        std::cout << "Two";
        break;
}

After displaying One, the break statement exits the switch.

6. The default Case

The default case executes when none of the case values match the switch expression.

int choice = 5;

switch (choice) {

    case 1:
        std::cout << "One";
        break;

    case 2:
        std::cout << "Two";
        break;

    default:
        std::cout << "Invalid choice";
}

7. Simple switch Example

int day = 3;

switch (day) {

    case 1:
        std::cout << "Monday";
        break;

    case 2:
        std::cout << "Tuesday";
        break;

    case 3:
        std::cout << "Wednesday";
        break;

    default:
        std::cout << "Invalid day";
}

The output is Wednesday.

8. switch with User Input

#include <iostream>

int main() {

    int choice;

    std::cout << "Enter choice: ";
    std::cin >> choice;

    switch (choice) {

        case 1:
            std::cout << "You selected option 1";
            break;

        case 2:
            std::cout << "You selected option 2";
            break;

        default:
            std::cout << "Invalid choice";
    }

    return 0;
}

9. switch with Character

A switch can also be used with a character value.

char grade = 'A';

switch (grade) {

    case 'A':
        std::cout << "Excellent";
        break;

    case 'B':
        std::cout << "Very Good";
        break;

    case 'C':
        std::cout << "Good";
        break;

    default:
        std::cout << "Other grade";
}

10. Multiple Cases

A switch statement can contain many case labels.

int number = 4;

switch (number) {

    case 1:
        std::cout << "One";
        break;

    case 2:
        std::cout << "Two";
        break;

    case 3:
        std::cout << "Three";
        break;

    case 4:
        std::cout << "Four";
        break;

    default:
        std::cout << "Other number";
}

11. What Happens Without break?

If break is omitted, execution can continue into the following case statements. This behavior is called fall-through.

int number = 1;

switch (number) {

    case 1:
        std::cout << "One";

    case 2:
        std::cout << "Two";
}

Here, after case 1 executes, execution continues into case 2 because there is no break between them.

12. Intentional Fall-Through

Sometimes multiple cases can intentionally share the same code.

int day = 6;

switch (day) {

    case 6:
    case 7:
        std::cout << "Weekend";
        break;

    default:
        std::cout << "Working day";
}

Both 6 and 7 execute the same block.

13. switch for Days of the Week

int day = 5;

switch (day) {

    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";
}

14. switch for Months

int month = 2;

switch (month) {

    case 1:
        std::cout << "January";
        break;

    case 2:
        std::cout << "February";
        break;

    case 3:
        std::cout << "March";
        break;

    default:
        std::cout << "Another month";
}

15. Simple Calculator Using switch

#include <iostream>

int main() {

    char op;
    double a, b;

    std::cout << "Enter operator (+, -, *, /): ";
    std::cin >> op;

    std::cout << "Enter two numbers: ";
    std::cin >> a >> b;

    switch (op) {

        case '+':
            std::cout << a + b;
            break;

        case '-':
            std::cout << a - b;
            break;

        case '*':
            std::cout << a * b;
            break;

        case '/':
            if (b != 0) {
                std::cout << a / b;
            }
            else {
                std::cout << "Cannot divide by zero";
            }
            break;

        default:
            std::cout << "Invalid operator";
    }

    return 0;
}

16. Menu Using switch

int choice = 2;

switch (choice) {

    case 1:
        std::cout << "Add Student";
        break;

    case 2:
        std::cout << "View Student";
        break;

    case 3:
        std::cout << "Delete Student";
        break;

    case 4:
        std::cout << "Exit";
        break;

    default:
        std::cout << "Invalid choice";
}

17. switch with Enum

A switch can be used with enumeration values.

enum Color {
    RED,
    GREEN,
    BLUE
};

Color color = GREEN;

switch (color) {

    case RED:
        std::cout << "Red";
        break;

    case GREEN:
        std::cout << "Green";
        break;

    case BLUE:
        std::cout << "Blue";
        break;
}

18. switch with const Values

Case labels must represent constant values known as case values.

const int ONE = 1;
const int TWO = 2;

int choice = 2;

switch (choice) {

    case ONE:
        std::cout << "One";
        break;

    case TWO:
        std::cout << "Two";
        break;
}

19. switch with Integer Values

int number = 10;

switch (number) {

    case 5:
        std::cout << "Five";
        break;

    case 10:
        std::cout << "Ten";
        break;

    case 15:
        std::cout << "Fifteen";
        break;

    default:
        std::cout << "Other value";
}

Integer values are commonly used with switch statements.

20. switch and if-else Comparison

An if-else ladder is useful for ranges and complex conditions. A switch is convenient when comparing one expression with specific fixed values.

Using if-else:

if (choice == 1) {
    std::cout << "One";
}
else if (choice == 2) {
    std::cout << "Two";
}

Using switch:

switch (choice) {

    case 1:
        std::cout << "One";
        break;

    case 2:
        std::cout << "Two";
        break;
}

21. switch with String-like Choices

A traditional C++ switch does not directly switch on std::string. For string comparisons, an if-else structure is commonly used.

std::string role = "admin";

if (role == "admin") {
    std::cout << "Admin";
}
else if (role == "student") {
    std::cout << "Student";
}

This is different from switching on an integer or character.

22. Nested switch

A switch statement can contain another switch statement.

int category = 1;
int choice = 2;

switch (category) {

    case 1:

        switch (choice) {

            case 1:
                std::cout << "Option 1";
                break;

            case 2:
                std::cout << "Option 2";
                break;

            default:
                std::cout << "Invalid option";
        }

        break;

    default:
        std::cout << "Invalid category";
}

Nested switches should be used carefully because too much nesting can make programs harder to read.

23. Practical Student Menu

#include <iostream>

int main() {

    int choice;

    std::cout << "1. Profile" << std::endl;
    std::cout << "2. Attendance" << std::endl;
    std::cout << "3. Fees" << std::endl;
    std::cout << "4. Logout" << std::endl;

    std::cout << "Enter choice: ";
    std::cin >> choice;

    switch (choice) {

        case 1:
            std::cout << "Opening Profile";
            break;

        case 2:
            std::cout << "Opening Attendance";
            break;

        case 3:
            std::cout << "Opening Fees";
            break;

        case 4:
            std::cout << "Logging out";
            break;

        default:
            std::cout << "Invalid choice";
    }

    return 0;
}

24. Practical ATM Menu

#include <iostream>

int main() {

    int choice;

    std::cout << "1. Check Balance" << std::endl;
    std::cout << "2. Deposit" << std::endl;
    std::cout << "3. Withdraw" << std::endl;
    std::cout << "4. Exit" << std::endl;

    std::cout << "Enter choice: ";
    std::cin >> choice;

    switch (choice) {

        case 1:
            std::cout << "Checking balance";
            break;

        case 2:
            std::cout << "Deposit selected";
            break;

        case 3:
            std::cout << "Withdraw selected";
            break;

        case 4:
            std::cout << "Exit";
            break;

        default:
            std::cout << "Invalid choice";
    }

    return 0;
}

25. Practical Traffic Signal Example

char signal = 'R';

switch (signal) {

    case 'R':
        std::cout << "Stop";
        break;

    case 'Y':
        std::cout << "Wait";
        break;

    case 'G':
        std::cout << "Go";
        break;

    default:
        std::cout << "Invalid signal";
}

26. Common switch Mistakes

  • Forgetting the break statement when it is needed.
  • Forgetting the default case when invalid values should be handled.
  • Using duplicate case values.
  • Using a case value that is not a suitable constant case label.
  • Forgetting the colon : after a case value.
  • Trying to use a traditional switch directly with std::string.
  • Creating unnecessarily complicated nested switch statements.

Correct case syntax:

case 1:
    std::cout << "Option 1";
    break;

27. Complete Calculator Example

#include <iostream>

int main() {

    double num1, num2;
    char operation;

    std::cout << "Enter first number: ";
    std::cin >> num1;

    std::cout << "Enter operator (+, -, *, /): ";
    std::cin >> operation;

    std::cout << "Enter second number: ";
    std::cin >> num2;

    switch (operation) {

        case '+':
            std::cout << "Result = " << num1 + num2;
            break;

        case '-':
            std::cout << "Result = " << num1 - num2;
            break;

        case '*':
            std::cout << "Result = " << num1 * num2;
            break;

        case '/':
            if (num2 != 0) {
                std::cout << "Result = " << num1 / num2;
            }
            else {
                std::cout << "Cannot divide by zero";
            }
            break;

        default:
            std::cout << "Invalid operator";
    }

    return 0;
}

28. When Should You Use switch?

A switch is useful when:

  • You are comparing one expression with fixed values.
  • You have several discrete choices.
  • You are creating a menu-driven program.
  • You are working with integer, character, or enumeration values.

For ranges such as marks >= 90, an if-else ladder is usually more suitable.

29. switch Best Practices

  • Use clear case labels.
  • Use break when you do not want fall-through.
  • Use default to handle unexpected choices when appropriate.
  • Keep each case simple and readable.
  • Use indentation consistently.
  • Avoid unnecessary nested switch statements.
  • Use if-else when conditions involve ranges or complex expressions.
switch (choice) {

    case 1:
        // action
        break;

    case 2:
        // action
        break;

    default:
        // invalid choice
}

30. switch Statement – Final Summary

Part Purpose
switch Starts the multi-choice selection.
case Defines a possible matching value.
break Exits the switch after a case executes.
default Runs when no case matches.
Fall-through Occurs when execution continues into the next case without a break.
switch (expression) {

    case value1:
        // statements
        break;

    case value2:
        // statements
        break;

    default:
        // default statements
}

📌 Key Points

  • The switch statement is used for multiple fixed choices.
  • The case keyword defines possible values.
  • The break statement normally prevents execution from continuing into the next case.
  • The default case handles values that do not match any case.
  • Multiple cases can share the same block of code.
  • Fall-through can occur when break is omitted.
  • Switch can be used with suitable integral, character, and enumeration values.
  • Traditional switch statements do not directly compare std::string values.
  • Switch is useful for menus and fixed-value choices.
  • Use if-else when you need ranges or complex conditions.

🧠 Quick Quiz

Question: Which keyword is normally used to stop execution after a matching case in a switch statement?