The break Statement in C++ - dummies

By Stephen R. Davis

Just as the default case is optional in C++, so the break at the end of each case is also optional. Without the break statement, however, control simply continues to move from one case to the next. Programmers say that control falls through. Falling through is most useful when two or more cases are handled in the same way.

For example, C++ may differentiate between upper- and lowercase characters in code, but most humans don’t. The following code snippet prompts the user to enter a C to create a checking account and an S to create a savings account. The user might enter a capital or lowercase letter. To keep C++ happy, the following snippet provides extra case statements to handle lowercase c and s:

cout << "Enter C to create checking account, "
     << "S to create a saving account, "
     << "and X to exit: ";
cin  >> cAccountType;
  case 'S':        // upper case S
  case 's':        // lower case s
     // creating savings account
  case 'C':        // upper case C
  case 'c':        // lower case c
    // create checking account
  case 'X':        // upper case X
  case 'x':        // lower case x
    // exit code goes here
    cout << "I didn't understand that" << endl;