How to Use the Switch Statement in C++ - dummies

How to Use the Switch Statement in C++

By Stephen R. Davis

The switch statement in C++ is a control statement that is useful in a limited number of cases. The switch statement resembles a compound if statement by including a number of different possibilities rather than a single test:

    case c1:
        // go here if the expression == c1
    case c2:
        // go here if expression == c2
        // go here if there is no match

The value of expression must be an integer (int, long, or char). The case values must be constants.

As of the ‘14 standard, they can also be a constant expression.

When the switch statement is encountered, the expression is evaluated and compared to the various case constants. Control branches to the case that matches. If none of the cases match, control passes to the default clause.

Consider the following example code snippet:

int choice;
cout << "Enter a 1, 2 or 3:";
cin  >> choice;
    case 1:
      // do "1" processing
    case 2:
      // do "2" processing
    case 3:
      // do "3" processing
      cout << "You didn't enter a 1, 2 or 3n";

Once again, the switch statement has an equivalent; in this case, multiple if statements. However, when there are more than two or three cases, the switch structure is easier to understand.

The break statements are necessary to exit the switch command. Without the break statements, control falls through from one case to the next. (Look out below!)