Switch Statement

The Switch statement is a selection statement that can be used instead of a series of If-Then-Else statements. Switch statements are much better for complex expressions. Alternative statements are listed with a switch label in front of each. A switch label is either a case label or the word default. A case label is the word case followed by a constant expression. An integral expression is called a switch expression is used to match one of the values on the case labels. The statement associated with the value that is matched is the statement that is executed. Execution then continues sequentially from the matched label untill the end of the Switch statement is encountered or a break statement is encountered. Here is the syntax template for the Switch statement:
switch ( IntegralOrEnumExpression )


SwitchLabel ... Statement
. }

IntegralOrEnumExpression is an expression of integral type - char, short, int, long, bool or of enum type which will be discussed in chapter 10.


	case ConstantExpression:
	default :
In a case label, ConstantExpression is an integral or enum expression whose operands must be literal or name named constants.

Now let's look at the following C++ code:

   switch (grade)
		case 'A': cout << "Great work. " << endl;
		case 'B': cout << "Good work. " << endl;
		case 'C': cout << "Passing work. " << endl;
		case 'D':
		case 'F': cout << "Unsatisfictory work. " << endl;
			  cout << "See your instructor." << endl;
		default:  cout << grade << " is not a legal grade." << endl;
grade is the switch expression; the the letters (such as A, B, C, D, F (also known as case value) beside the statements make up the case labels. The value in grade is compared with the value in each case label. When a match is found, the corresponding statement is executed. If the value of the switch expression does not match a value in any case label, the default label is matched by default. Because execution continues after a match until break is encountered, both 'D' and 'F' send the same message to the screen. What would happen if we forgot to put break after the statement associated with case 'B'? Every time grade contained a B both "Good work!" and "Passing work!" would be printed.

Copyright: Department of Computer Science, University of Regina.