Switch Statement in C++ with example

Switch Statement
Switch Statement

Switch Statement is used when we have multiple conditions and we need to perform different actions based on the conditions. 

Switch is similar to ifelse statements but limited to constant expressions.

Q: What is a constant expression in C++?
Q: What is a constant expression in C++?

Ans: When only constants are present in the expression then that expression is called constant expression.

In C++ constant expression can contain only integers and characters.

An output of the constant expression can be:

  1. An integer constant Ex: 1, 556, 988
  2. A character constant Ex: ‘A’ , ‘a’

Syntax
Syntax

It’s most typical syntax is:

switch (expression){  case constant expression 1:     group-of-statements-1;     break;  case constant expression 2:     group-of-statements-2;     break;  .  .  .  default:     default-group-of-statements}

Switch and if else
Switch and if else

Both of the following code have the same behavior, demonstrating the if-else equivalent of a switch statement:

switch exampleif-else equivalent
switch (x) {  case 1:    cout << "x is 1";    break;  case 2:    cout << "x is 2";    break;  default:    cout << "value of x unknown";  }
if (x == 1) {  cout << "x is 1";}else if (x == 2) {  cout << "x is 2";}else {  cout << "value of x unknown";}

Example of Switch Case
OUTPUT
Example of Switch Case

#include<iostream>using namespace std;int main () {   char grade = 'A';   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;}

OUTPUT

ExcellentYour grade is A

Important Notes
Important Notes

1. break keyword is used to come out switch statement.

2. If we will not use break keyword then all consecutive case statements will get executed.

Exmaple:

#include<iostream>using namespace std;int main(){   int val=3;   switch(val) {      case 1: cout<<"Case1 "<<endl;      case 2: cout<<"Case2 "<<endl;      case 3: cout<<"Case3 "<<endl;      case 4: cout<<"Case4 "<<endl;      default: cout<<"Default "<<endl;    }   return 0;}

Output:

Case3 Case4 Default