C++ Switch Case : Statement
C++ provides the multi-way decision statement which helps to decrease the complexity of the program.
Switch case statement is best way to deal with the else-if nesting.
if(Condition 1) Statement 1 else { Statement 2 if(condition 2) { if(condition 3) statement 3 else if(condition 4) { statement 4 } } else { statement 5 } }
Consider the above scenario, we can overcome this situation by using the switch case statement syntax like below -
Table of content
C++ Switch Case Syntax :
switch(expression) { case value1 : body1 break; case value2 : body2 break; case value3 : body3 break; default : default-body break; } next-statement;
Flow Diagram :
Example :
#include <iostream> using namespace std; int main () { // local variable declaration: char grade = 'C'; switch(grade) { case 'A' : cout << "A grade" << endl; break; case 'B' : cout << "B grade" << endl; break; case 'C' : cout << "C grade" << endl; break; case 'D' : cout << "D grade" << endl; break; case 'F' : cout << "E grade" << endl; break; default : cout << "Invalid grade" << endl; } cout << "Your grade is " << grade << endl; return 0; }
Output :
C grade Your grade is C
Some rules of using Switch Statement :
The following rules apply to a switch statement:
- Case Label must be unique
- Case Labels must ends with Colon
- Case labels must have constants / constant expression
- Case label must be of integral Type ( Integer,Character)
- Switch case should have at most one default label
- Default label is Optional
- Default can be placed anywhere in the switch
- Break Statement takes control out of the switch
- Two or more cases may share one break statement
- Nesting ( switch within switch ) is allowed.
- Relational Operators are not allowed in Switch Statement.
- Macro Identifier are allowed as Switch Case Label.
- Const Variable is allowed in switch Case Statement.
- Empty Switch case is allowed.