Switch Statement

The switch statement is a selection statement that can be used instead of a series of if-else if-else statements. Switch statements are often much simpler than if statements when there are many options.

Alternative statements are listed with a label in front of each. A label can be either a case label or a default label. A case label is the word case followed by a constant integer expression, then a colon :. The value of the switch variable integer expression is used to match one of the values on the case labels. The statement after the label that is matched is executed. Execution 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 ( variable_integer_expression )
{

    case constant_integer_expression : // there's usually at least one case label
      // optional statements

    //repeat case labels and statements as needed
      .
      .
      .

    default: // optional, can appear anywhere but only once per switch statement
      // optional statements
    
}

variable_integer_expression is any expression of integral type - char, int, long, bool, or enum.

Break Statements

  
    {
      .
      .
      .
      break; constant_integer_expression:
      .
      .
      .
    }

A break statement will cause execution to jump to the end of a block of statements. break statements are often used to end case labels in switch statements.

Now let's look at an example:

  
   switch (grade)
	{
		case 'A': 
        cout << "Great work. " << endl;
        break;
		case 'B': 
        cout << "Good work. " << endl;
        break;
		case 'C': 
        cout << "Passing work. " << endl;
        break;
		case 'D':
		case 'F': 
        cout << "Unsatisfictory work. " << endl;
        cout << "See your instructor." << endl;
        break;
		default:  
        cout << grade << " is not a legal grade." << endl;
        break;
	}

 


 

©Department of Computer Science, University of Regina.