The switch Statement

The switch statement is a composite statement generally used when there are a large number of alternatives to choose from. This type of processing can also be accomplished using an if/else statement, but the syntax and meaning is much cleaner and easier to understand when implemented in the form of a switch. In a switch statement, a condition, or expression, is evaluated. From this condition, a separate case statement is defined for every possible value that is of ordinal type. (ie. integer, char, boolean)

Below is a sample switch statement from a small program. (Pascal uses a similar structure for its case statement)

switch (value) // "value" declared as an integer
   case 1:   cout << "First statement." << endl;
   case 2:   cout << "Second statement." << endl;
   default:  cout << "No statement here." << endl;
} // switch

When value = 1, The line "First statement." will be printed. The keyword break causes the switch to terminate, and appears at the end of every case statement, with the exception of the default case. Doing this prevents the program from executing any further case statements. Otherwise, the program will follow statements one after another until it reaches the next break. The program will then resume with the next statement (if any) following the switch statement.

The keyword default appears at the end of the switch statement. This part covers all of the remaining values not used throughout the duration of the switch statement. In our small example, the default setting is the line "No statement here.", and is executed whenever value is neither 1 nor 2. (ie. every other possible integer)

The most common use of the switch statement is with menu-driven operating systems. Here, a selection is made from a number of choices displayed on a menu, and an action is executed based on the end user's choice. This type of format can go through an infinite number of selections, and will quit whenever the end user wants to.
Click here for an example of a program that uses a menu-driven system.

This page has been accessed     times.
Last modified: Sunday, 25-Mar-2012 17:19:00 CST
Copyright 2000 Department of Computer Science, University of Regina.

 CS Dept Home Page

Teaching Material