Switch Case in C++

A switch statement allows a variable to be tested for equality against an inventory of values. Each value is named a case, and therefore the variable being switched on is checked for every case.

C++ if...else...if statement allows you to execute a block code among many alternatives. If you are checking on the value of a single variable in C++ if...else...if, it is better to use switch statement.

The switch statement is often faster than C++ if...else...if.

Syntax: -

switch(expression)
{
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional
default : //optional
statement(s);
}


The following rules apply to a switch statement −
  • expression utilized in a switch statement must have an integral or enumerated type
  • You can have any number of case statements within a switch. Each case is followed by the worth to be compared to and a colon.
  • constant-expression for a case must be an equivalent data type because the variable within the switch
  • When the variable being switched on is adequate to a case, the statements following that case will execute until an opportunity statement is reached.
  • When an break statement is reached, the switch terminates, and therefore the flow of control jumps to subsequent line
  • If no break appears, the flow of control will fall flat to subsequent cases until an break is reached.
  • A switch statement can have an optional default case, which must appear at the top of the switch. The default case are often used for performing a task when none of the cases is true.

Flow-Chart -

switch case in c++
Switch Case Flowchart
Example: -

#include <iostream>
using namespace std;

int main() {
int n;
cout <<"Enter Number:";
cin >>n;
switch(n)
{
case 1:
cout <<"Number is 1";
break;
case 2:
cout <<"Number is 2";
break;
case 3:
cout <<"Number is 3";
break;
case 4:
cout <<"Number is 4";
break;
case 5:
cout <<"Number is 5";
break;
default :
cout <<"Number is not 1,2,3,4 & 5";
}
}


Output:
Enter Number:
3
Number is 3


2 Comments

Click here for Comments
Ariza
admin
June 9, 2020 at 12:00 AM ×

In a switch maximum case can be 2^32+1.

Reply
avatar
Raj Kamariya
admin
June 12, 2020 at 7:53 PM ×

Standard C++ recommends that at least 16,384 case statements be supported!

Reply
avatar