C++ switch Statement

The switch is a multi way selection statement.

Using the switch statement, one can select only one option from more number of options. In the switch statement, we provide a value that is compared with a value associated with each option. Whenever the given value matches the value associated with an option, the execution starts from that option. In the switch statement, each option is defined as a case.
The switch statement has the following syntax and execution flow diagram.

switch statement syntax
Syntax - if Statement
switch (key_value) {

  case value_1: 
            // block of code 1
            break;

  case value_2: 
            // block of code 2
            break;

  case value_3: 
            // block of code 3
            break;

  case value_4: 
            // block of code 4
            break;

  ...

  default: default block of code

}

Let's look at the following code.

Example - Code to illustrate the if statement and condition
#include <iostream>

using namespace std;

int main()
{
    int key_value;

    cout << endl << "Enter any digit: ";
    cin >> key_value;

    switch( key_value ) {
		   	case 0: cout << "ZERO"  << endl;
                    break ;
		   	case 1: cout << "ONE"  << endl;
                    break ;
		   	case 2: cout << "TWO"  << endl;
                    break ;
		   	case 3: cout << "THREE"  << endl;
                    break ;
		   	case 4: cout << "FOUR"  << endl;
                    break ;
		   	case 5: cout << "FIVE"  << endl;
                    break ;
		   	case 6: cout << "SIX"  << endl;
                    break ;
		   	case 7: cout << "SEVEN"  << endl;
                    break ;
		   	case 8: cout << "EIGHT"  << endl;
                    break ;
		   	case 9: cout << "NINE"  << endl;
                    break ;
		   	default: cout << "Not a Digit"  << endl;
		   }

    return 0;
}
Output
switch statement example program in c++

When we use switch statement we must follow the following points.

  • The case values must be either integer or character or boolean but not any other data type like string, float, double, etc,.
  • The expression provided in the switch should result in a constant value of integer or character or boolean otherwise it would not be valid.
  • Duplicate case values are not allowed.
  • Both switch and case are keywords so they must be used only in lower case letters.
  • The data type of case value and the value specified in the switch statement must be the same.
  • The keyword case and its value must be superated with a white space.
  • The case values need not be defined in sequence, they can be in any order.
  • The default case is optional and it can be defined anywhere inside the switch statement.
  • The switch value might be direct, a variable or an expression.
  • Nesting of switch statements are allowed.