C++ Switch Case : Statement



C++ provides the multi-way decision statement which helps to decrease the complexity of the program.

Switch case statement is best way to deal with the else-if nesting.

if(Condition 1)
   Statement 1
else   
   {
   Statement 2
   if(condition 2)
      {
      if(condition 3) 
        statement 3
      else
         if(condition 4)
            {
            statement 4
            }         
      }
   else
     {
     statement 5
     }
   }

Consider the above scenario, we can overcome this situation by using the switch case statement syntax like below –

C++ Switch Case Syntax :

switch(expression)
{
case value1 : 
    body1
    break;

case value2 : 
    body2
    break;

case value3 : 
    body3
    break;

default :
    default-body
    break;  
}
next-statement;

Flow Diagram :

Syntax of Switch Case Stetement in C Programming
*Steps are Shown in Circles.

Example :

#include <iostream>
using namespace std;
 
int main ()
{
   // local variable declaration:
   char grade = 'C';

   switch(grade)
   {
   case 'A' :
      cout << "A grade" << endl; 
      break;
   case 'B' :
      cout << "B grade" << endl;
      break;
   case 'C' :
      cout << "C grade" << endl; 
      break;
   case 'D' :
      cout << "D grade" << endl; 
      break;
   case 'F' :
      cout << "E grade" << endl; 
      break;
   default :
      cout << "Invalid grade" << endl;
   }
   cout << "Your grade is " << grade << endl;
 
   return 0;
}

Output :

C grade
Your grade is C

Some rules of using Switch Statement :

The following rules apply to a switch statement:

  1. Case Label must be unique
  2. Case Labels must ends with Colon
  3. Case labels must have constants / constant expression
  4. Case label must be of integral Type ( Integer,Character)
  5. Switch case should have at most one default label
  6. Default label is Optional
  7. Default can be placed anywhere in the switch
  8. Break Statement takes control out of the switch
  9. Two or more cases may share one break statement
  10. Nesting ( switch within switch ) is allowed.
  11. Relational Operators are not allowed in Switch Statement.
  12. Macro Identifier are allowed as Switch Case Label.
  13. Const Variable is allowed in switch Case Statement.
  14. Empty Switch case is allowed.