C++ switch Control Statement
The
switch control statement allows checking the variable for equality against a list of values. The
switch statement checks an
integer, char or enumerated type in its condition expression. It does not take any floating variable in its condition expression.
Syntax
switch(expression)
{
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional
……
default : //Optional
statement(s);
}
C++ switch Example
#include <iostream>
using namespace std;
int main () {
char grade;
cout<<"enter any grade A,B,C,D" << endl;
cin>> grade;
switch(grade) {
case 'A' :
cout << "your grade is A" << endl;
break;
case 'B' :
cout << "your grade is B" << endl;
break;
case 'C' :
cout << "your grade is C" << endl;
break;
case 'D' :
cout << "your grade is D" << endl;
break;
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;
return 0;
}
Output
enter any grade A,B,C,D
C
your grade is C