Skip to content
Artemis edited this page May 13, 2023 · 2 revisions

Switch in C++

The C++ switch statement is used to execute a block of code based on the value of an expression. It can be used as an alternative to an if-else statement, and is often easier to read and understand.

Syntax

The syntax for a switch statement in C++ is as follows:

switch (expression)
{
    case value1:
        // code to be executed if expression == value1;
        break;
    case value2:
        // code to be executed if expression == value2;
        break;
    default:
        // code to be executed if expression != value1 || value2;
}

The expression in a switch statement is typically an integer, character, or string. The case labels must be constants with values that match the expression. The default label is optional and will execute if none of the case labels match the expression.

Examples

Example 1

int num = 5;

switch (num)
{
    case 1:
        cout << "The number is 1";
        break;
    case 5:
        cout << "The number is 5";
        break;
    default:
        cout << "The number is not 1 or 5";
}

In the above example, the expression num evaluates to 5, so the code inside the case 5 label will be executed.

Example 2

char letter = 'A';

switch (letter)
{
    case 'A':
        cout << "The letter is A";
        break;
    case 'B':
        cout << "The letter is B";
        break;
    default:
        cout << "The letter is not A or B";
}

In the above example, the expression letter evaluates to 'A', so the code inside the case 'A' label will be executed.

Clone this wiki locally