C++ switch Statement
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:
The expression in a switch statement must be an integral or enumerated type, or a class type where the class has a single conversion function to an integral or enumerated type.
A switch can have any number of case statements. Each case is followed by the value to be compared and a colon.
The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is encountered.
When a break statement is encountered, the switch terminates, and the control flow jumps to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the control flow will fall through to subsequent cases until a break is encountered.
A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
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