11. Switch Statements

The purpose of a switch statement is to enable a program to decide between statements to execute. A switch is limited to making a decision based upon a set of integer values.

General Form

The general form of a switch statement is as follows:

switch (integer-variable) {
    case integer-constant-1:
        statements
        break;
    case integer-constant-2:
        statements
        break;
    ...
    default:
        default-statements
}

Some important points:

Do not put a semicolon after the closing parenthesis at the top of the switch statement. If a semicolon is placed there accidentally, the program will not compile.

The statements within the braces should be aligned as shown to visually emphasize their organization.

Since every expected integer value is explicitly stated, switch statements are not the best choice when a large range of integers must be accounted for (e.g., from 1 to 100). An if statement is a better choice.

How a Switch Statement Works

The steps taken when a switch statement executes are as follows:

  1. The integer variable’s value is compared to the integer constants starting at the first case and moving downward.
  2. If the variable’s value matches a constant:

    1. The statements in that case section of the switch statement are executed.
    2. The break statement causes execution of the switch to end passing execution to the first executable statement after the closing brace of the switch statement.
  3. If the variable’s value does not match any of the constants:

    1. The statements in the default section of the switch statement are executed.
    2. Execution of the switch ends passing execution to the first executable statement after the closing brace of the switch statement.

The keywords switch, case, and default do not perform any action. They only indicate the beginning of a switch statement’s sections.

If a break statement is accidentally omitted, execution of the statements in the switch will continue until a break statement in a subsequent section is executed or the end of the switch is reached (whichever comes first). The case keyword will not cause execution of statements in the switch to end.

Example

The example that follows is a switch statement version of the two examples in the If Statements section. All three versions are functionally equivalent (i.e., do the same thing). Step through the code by following the steps above. What would execution be like if the second break statement was accidentally omitted and the user entered 2?

int choice;

std::cout << "Your choice (1, 2, or 3): ";
std::cin >> choice;

switch (choice) {
    case 1:
        std::cout << "This is the best choice!" << std::endl;
        break;
    case 2:
        std::cout << "This is the second best choice!"
                  << std::endl;
        break;
    case 3:
        std::cout << "Oh well..." << std::endl;
        break;
    default:
        std::cout << "Oops!!!"<< std::endl;
}