Pages

C++ Switch

What is C++ Switch?  

Switch case statements are a substitute for long if statements that compare a variable to several integer of character. The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant.

Switch Statement Flow Diagram
C++ Switch Statement Flowchart Diagram
Switch Statement Flow Diagram


Syntax: 

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);
}


Example:


#include <iostream>
using namespace std;
int main()
{
   int number = 2;
   switch (number) // expression
   {
       case 1: cout<<"Choice is 1"; // case 1 condition
               break;
       case 2: cout<<"Choice is 2"; // case 2 condition
                break;
       case 3: cout<<"Choice is 3"; // case 3 condition
               break;
       // deafult output
       default: cout<<"Choice other than 1, 2 and 3"; 
                break; 
   }
   return 0;

}

Output:












<< C++ If Statements       --        C++ For Loop>>