Easy Tutorial
❮ Cpp Useful Resources Cpp Decision ❯

C++ switch Statement

C++ Decision

A switch statement allows testing a variable against multiple values. Each value is called a case, and the variable being switched on is checked against each switch case.

Syntax

The syntax for a switch statement in C++ is:

switch(expression){
    case constant-expression  :
       statement(s);
       break; // Optional
    case constant-expression  :
       statement(s);
       break; // Optional

    // You can have any number of case statements
    default : // Optional
       statement(s);
}

switch statements must follow these rules:

Flowchart

Example

Example

#include <iostream>
using namespace std;

int main ()
{
   // Local variable declaration
   char grade = 'D';

   switch(grade)
   {
   case 'A' :
      cout << "Excellent!" << endl; 
      break;
   case 'B' :
   case 'C' :
      cout << "Well done" << endl;
      break;
   case 'D' :
      cout << "You passed" << endl;
      break;
   case 'F' :
      cout << "Better try again" << endl;
      break;
   default :
      cout << "Invalid grade" << endl;
   }
   cout << "Your grade is " << grade << endl;

   return 0;
}

When the above code is compiled and executed, it produces the following result:

You passed
Your grade is D

C++ Decision

❮ Cpp Useful Resources Cpp Decision ❯