C++ Switch Statement

The switch statement in C++ is used to select one of many code blocks to execute. It is often used as an alternative to multiple if…else statements when checking a variable against several constant values.

Syntax of Switch Statement

switch(expression) {
    case value1:
        // code block
        break;

    case value2:
        // code block
        break;

    case value3:
        // code block
        break;

    default:
        // default code block
}

Explanation

  • expression – The value that will be checked in the switch statement.
  • case – Represents different possible values for the expression.
  • break – Stops execution and exits the switch block.
  • default – Executes if none of the cases match the expression.

Example Program

#include <iostream>
using namespace std;

int main() {

    int day = 3;

    switch(day) {
        case 1:
            cout << "Monday";
            break;

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

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

        case 4:
            cout << "Thursday";
            break;

        case 5:
            cout << "Friday";
            break;

        default:
            cout << "Weekend";
    }

    return 0;
}

Output

Wednesday

Important Notes

  • The break statement is used to stop the execution of the switch block.
  • If break is not used, execution continues to the next case. This is called fall-through.
  • The default case is optional but recommended to handle unexpected values.
  • The switch statement works mainly with int, char, and enum values.

Next Topic

Next, learn about C++ Loops.