C++ tutorial: switch


Use 'switch' to select from a set of statement groups
'if...else' is useful for situations where there is a clear choice between executing one set of statements or another. 'switch' covers the situation where there may be many different alternatives, and it would be ugly to use a large number of 'ifs' and 'elses'. The stucture of the switch statment is:

switch (expression)
     {
     case value1:
	    // Execute these statements if expression is equal to 'value1'
	    // ...
         break;

     case value2:
	    // Execute these statements if expression is equal to 'value2'
	    // ...
         break;

     default:
         // These statements executed if none of the others are
     }

The switch statement starts with the line:

switch (expression)

Where 'expression' is the expression to be tested. This may be a simple variable, like a character indicating the user's selection from a menu, or a mathematical expression of any complexity. It may not, however, be non-number. This means that you can't use 'switch' to compare strings, just like you can't use 'if' for this.

Depending on the value of 'expression' one of the following 'cases' will be executed. If none of the cases has the same value as 'expression' then the 'default' case will be executed.

A common error when using 'switch' is to forget that execution will start in the selected case, then continue until 'break'. If you miss out the 'break', execution will continue into the next case.

The program menu.cpp demonstrates the use of 'switch', along with some other concepts that haven't been covered yet. In the function 'main', the user is asked to enter a letter to make a choice from a menu.

     cin >> Choice;
     Choice = toupper (Choice);

This letter is then used in a 'switch ' statement to select the appropriate action.

     switch (Choice)
         {
         case 'A': FunctionA(); break;
         case 'B': FunctionB(); break;
         case 'C': break; // Do nothing, program will exit
         default:         // Program should handle the case where the user enters an invalid character
              cout << "Sorry, '" << Choice << "' does not correspond to a function. Please try again.\n\n";
         }

In this case the 'default' is used to handle the situation where the user enters something which is not a valid selection.

©1994-2003 Kevin Boone, all rights reserved