Switch Statement

Sometimes you compare one value against a list of exact options: menu choice 1, 2 or 3, or a month from 1 to 12. An else-if ladder works, but you repeat choice == on every line. The switch statement is made for this case.

#include <iostream>
using namespace std;

int main() {
    int choice = 2;
    switch (choice) {
        case 1:
            cout << "Small" << "\n";
            break;
        case 2:
            cout << "Medium" << "\n";
            break;
        case 3:
            cout << "Large" << "\n";
            break;
        default:
            cout << "Unknown size" << "\n";
    }
    return 0;
}

Output:

Medium

C++ compares the value in the parentheses with each case label. When one matches, it jumps to that line and runs the code there. default works like the final else of a ladder: it runs when no case matches.

Each case label must be a fixed value, like case 2:. A switch can only ask "is it exactly this value?". It cannot test ranges like < 15, so for ranges you still need an else-if ladder.

Do not forget break

break ends the switch. Without it, C++ does not stop at the end of the matching case. It keeps going and runs the code of the cases below it too. Here is the same program with every break removed:

int choice = 2;
switch (choice) {
    case 1:
        cout << "Small" << "\n";
    case 2:
        cout << "Medium" << "\n";
    case 3:
        cout << "Large" << "\n";
    default:
        cout << "Unknown size" << "\n";
}

Output:

Medium
Large
Unknown size

The program started at case 2 and then ran through case 3 and default. This is called fall-through. The compiler gave no warning. If a switch prints more lines than you expected, look for a missing break.

Fall-through has one good use. Sometimes two labels should run the same code. Write the labels one after the other. This also shows that a switch works with char values:

char answer = 'Y';
switch (answer) {
    case 'y':
    case 'Y':
        cout << "Yes" << "\n";
        break;
    default:
        cout << "No" << "\n";
}

Output:

Yes

A switch works with whole numbers and characters. It does not work with a string. If you try, the program does not compile, and the error says switch quantity not an integer.

In the exercise, finish a switch that turns the numbers 1 to 7 into days of the week.