Home C++ switch statement in C++ tutorial with code examples

switch statement in C++ tutorial with code examples

The switch statement in C++ is a control structure that allows you to execute one of many code blocks based on the value of an expression. It’s often used as an alternative to multiple if-else statements, making the code more readable and efficient when checking a variable against multiple possible values.

Basic Syntax of the switch Statement

switch (expression) {
    case constant1:
        // Code to execute if expression == constant1
        break;
    case constant2:
        // Code to execute if expression == constant2
        break;
    ...
    default:
        // Code to execute if no cases match
}
  • Expression: The value that is compared against each case. It must be of an integral or enumeration type (such as int, char).
  • Case labels: Each case defines a possible value for the expression and the corresponding code to execute.
  • Break statement: Ends each case. Without break, execution continues to the next case (known as fall-through).
  • Default case: Executes if none of the cases match the expression. It’s optional but recommended.

1. Basic switch Statement Example

A simple switch statement that prints a message based on the value of a char variable.

#include <iostream>
using namespace std;

int main() {
    char grade = 'B';

    switch (grade) {
        case 'A':
            cout << "Excellent!" << endl;
            break;
        case 'B':
            cout << "Good job!" << endl;
            break;
        case 'C':
            cout << "Well done!" << endl;
            break;
        default:
            cout << "Invalid grade." << endl;
    }

    return 0;
}

Explanation:

  • The switch statement compares grade against each case. If grade is ‘B’, it prints “Good job!” and breaks out of the switch.

Output:

Good job!

2. switch Statement with Integer Cases

A switch statement that checks an integer value and performs an action based on its value.

#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;
        case 4:
            cout << "Thursday" << endl;
            break;
        case 5:
            cout << "Friday" << endl;
            break;
        default:
            cout << "Weekend!" << endl;
    }

    return 0;
}

Explanation:

  • Each case corresponds to a day of the week. If day is 3, it prints “Wednesday.”

Output:

Wednesday

3. switch Statement with default Case

The default case is executed if none of the cases match the expression.

#include <iostream>
using namespace std;

int main() {
    int option = 5;

    switch (option) {
        case 1:
            cout << "Option 1 selected." << endl;
            break;
        case 2:
            cout << "Option 2 selected." << endl;
            break;
        default:
            cout << "Invalid option." << endl;
    }

    return 0;
}

Explanation:

  • Since option is 5, which doesn’t match any case, the default case is executed, printing “Invalid option.”

Output:

Invalid option.

4. switch Statement with Multiple Statements in a Case

A case in a switch statement can contain multiple lines of code.

#include <iostream>
using namespace std;

int main() {
    int choice = 1;

    switch (choice) {
        case 1:
            cout << "Choice 1 selected." << endl;
            cout << "You have selected option 1." << endl;
            break;
        case 2:
            cout << "Choice 2 selected." << endl;
            cout << "You have selected option 2." << endl;
            break;
        default:
            cout << "Invalid choice." << endl;
    }

    return 0;
}

Explanation:

  • When choice is 1, both statements under case 1 are executed.

Output:

Choice 1 selected.
You have selected option 1.

5. switch Statement with Fall-Through Behavior

If you omit the break statement, the switch statement will continue executing the next cases until a break or the end of the switch.

#include <iostream>
using namespace std;

int main() {
    int number = 2;

    switch (number) {
        case 1:
            cout << "One" << endl;
        case 2:
            cout << "Two" << endl;
        case 3:
            cout << "Three" << endl;
        default:
            cout << "Default case" << endl;
    }

    return 0;
}

Explanation:

  • Because there’s no break after case 2, execution “falls through” to case 3 and default.

Output:

Two
Three
Default case

6. Grouping Cases

You can group multiple cases together if they perform the same action.

#include <iostream>
using namespace std;

int main() {
    char letter = 'A';

    switch (letter) {
        case 'A':
        case 'E':
        case 'I':
        case 'O':
        case 'U':
            cout << "The letter is a vowel." << endl;
            break;
        default:
            cout << "The letter is a consonant." << endl;
    }

    return 0;
}

Explanation:

  • If letter is any of the vowels (‘A’, ‘E’, ‘I’, ‘O’, ‘U’), it prints “The letter is a vowel.”

Output:

The letter is a vowel.

7. switch Statement with User Input

You can use a switch statement to respond to user input.

#include <iostream>
using namespace std;

int main() {
    int choice;

    cout << "Enter 1, 2, or 3: ";
    cin >> choice;

    switch (choice) {
        case 1:
            cout << "You selected option 1." << endl;
            break;
        case 2:
            cout << "You selected option 2." << endl;
            break;
        case 3:
            cout << "You selected option 3." << endl;
            break;
        default:
            cout << "Invalid choice." << endl;
    }

    return 0;
}

Explanation:

  • The user’s input determines which case executes. If the input isn’t 1, 2, or 3, it defaults to “Invalid choice.”

Sample Output:

Enter 1, 2, or 3: 2
You selected option 2.

8. Using switch to Evaluate an Enumeration

Enumerations (enums) can be used in a switch statement, as they are integral types.

#include <iostream>
using namespace std;

enum Direction { NORTH, SOUTH, EAST, WEST };

int main() {
    Direction dir = SOUTH;

    switch (dir) {
        case NORTH:
            cout << "Heading North" << endl;
            break;
        case SOUTH:
            cout << "Heading South" << endl;
            break;
        case EAST:
            cout << "Heading East" << endl;
            break;
        case WEST:
            cout << "Heading West" << endl;
            break;
    }

    return 0;
}

Explanation:

  • dir is an enum of type Direction. switch compares it to each Direction case.

Output:

Heading South

9. Using switch for Simple Calculations

The switch statement can handle simple calculations based on user input.

#include <iostream>
using namespace std;

int main() {
    char op;
    double num1, num2;

    cout << "Enter an operator (+, -, *, /): ";
    cin >> op;
    cout << "Enter two numbers: ";
    cin >> num1 >> num2;

    switch (op) {
        case '+':
            cout << "Result: " << num1 + num2 << endl;
            break;
        case '-':
            cout << "Result: " << num1 - num2 << endl;
            break;
        case '*':
            cout << "Result: " << num1 * num2 << endl;
            break;
        case '/':
            if (num2 != 0)
                cout << "Result: " << num1 / num2 << endl;
            else
                cout << "Cannot divide by zero." << endl;
            break;
        default:
            cout << "Invalid operator." << endl;
    }

    return 0;
}

Explanation:

  • The user inputs an operator and two numbers, and the switch performs the operation.
  • The default case handles invalid operators, and a conditional check prevents division by zero.

Sample Output:

Enter an operator (+, -, *, /): *
Enter two numbers:

 4 5
Result: 20

10. Summary Table

Use Case Code Example Description
Basic switch statement switch(x) { case … } Executes code based on x
Integer cases case 1: … case 2: … Matches integer values
Default case default: … Runs if no case matches
Multiple statements case 1: …; …; break; Multiple lines in one case
Fall-through Omit break Executes subsequent cases
Grouping cases case ‘A’: case ‘E’: Groups cases with same action
User input switch switch(userInput) {…} Responds to user input
Enum with switch switch(enumValue) {…} Compares enum values
Simple calculations switch(operator) {…} Switch based on operation

Complete Example: Switch Statement with Multiple Uses

This example demonstrates a switch statement handling different cases, including user input, fall-through behavior, and a default case.

#include <iostream>
using namespace std;

int main() {
    int menuOption;

    cout << "Select an option (1, 2, or 3): ";
    cin >> menuOption;

    switch (menuOption) {
        case 1:
            cout << "Option 1: View Account" << endl;
            break;
        case 2:
            cout << "Option 2: Deposit Money" << endl;
            cout << "Deposit feature is selected." << endl;
            break;
        case 3:
            cout << "Option 3: Withdraw Money" << endl;
            break;
        default:
            cout << "Invalid option selected." << endl;
    }

    return 0;
}

Explanation:

  • The user selects a menu option, and the switch statement directs them to the appropriate action.
  • If the option is not 1, 2, or 3, it falls to the default case.

Sample Output:

Select an option (1, 2, or 3): 2
Option 2: Deposit Money
Deposit feature is selected.

The switch statement in C++ provides an efficient and clean way to handle multiple conditions, especially when dealing with multiple fixed values.

You may also like