The switch Statement Enables You to Control Flow in C++ - dummies

The switch Statement Enables You to Control Flow in C++

By Stephen R. Davis

A program sometimes has to decide on one option out of a large number of possible legal inputs. C++ provides a convenient control mechanism for selecting among multiple options: the switch statement. The switch statement has the following format:

  case const1:
    // go here if expression == const1
  case const2:
    // go here if expression == const2
  case const3:         // repeat as often as you like
    // go here if expression == const3
    // go here if none of the other cases match

Upon encountering the switch statement, C++ evaluates expression. It then passes control to the case with the same value as expression. Control continues from there to the break statement, which transfers control to the } at the end of the switch statement. If none of the cases match, control passes to the default case.

The default case is optional. If the expression doesn’t match any case and no default case is provided, control passes immediately to the }.

Consider the following example code snippet:

int nMonth;
cout << "Enter the number of the month: ";
cin  >> nMonth;
switch (nMonth)
  case  1:
    cout << "It's January"  << endl;
  case  2:
    cout << "It's February" << endl;;
  case  3:
    cout << "It's March"    << endl;;
  case  4:
    cout << "It's April"    << endl;;
  case  5:
    cout << "It's May"      << endl;;
  case  6:
    cout << "It's June"     << endl;;
  case  7:
    cout << "It's July"     << endl;;
  case  8:
    cout << "It's August"   << endl;;
  case  9:
    cout << "It's September"<< endl;;
  case 10:
    cout << "It's October"  << endl;;
  case 11:
    cout << "It's November" << endl;;
  case 12:
    cout << "It's December" << endl;;
    cout << "That's not a valid month" << endl;;

You get the following output from the program when inputting a value of 3:

Enter the number of the month: 3
It's March
Press Enter to continue . . .

The figure shows how control flowed through the switch statement to generate the earlier result of March.


A switch statement is not like a series of if statements. For example, only constant integers or characters are allowed after the case keyword (that is expressions that can be completely evaluated at build time). You cannot supply an run time expression after a case. Thus, the following is not legal:

// cases cannot be expressions; the
// following is not legal for m declared as an int
  case m:
    cout << "n is equal to m" << endl;
  case 2 * m:
    cout << "n is equal to 2m" << endl;
  case 3 * m:
    cout << "n is equal to 3m" << endl;

Each of the cases must have a value at build time. The value of m is not known until the program executes.

Actually, the 2011 C++ standard introduces a constant expression type that can be used as the target of a case statement.