- A multibranch selection control structure
- Similar to nested if statements
|
- The Expression must be of type: char, short, int, long (not float, double, etc. !!!)
- The ConstantExpression must be a constant of type char, short, int, long (not float, double, etc. !!) or the keyword default
- An example
switch (grade) { case 'A': cout << "Very good work !!" << endl; case 'B': cout << "Good work !!" << endl; case 'C': cout << "Average work !!" << endl; case 'D': cout << "Poor work !!" << endl; case 'F': cout << "Very poor work !!" << endl; default: cout << grade << " is not a legal letter" << endl; } cout << "End of grade assignment" << endl;
- Each case label (ConstantExpression) cannot appear more than once
- The default label is optional but no more than one default is allowed
- The flow of control continues from the selected case until the end of the switch statement
- A single statement may be preceded by more than one case label
- Each case can include more than one statements (no braces are needed !!)
switch (grade) { case 'A': case 'B': cout << "Good work !!" << endl; case 'C': case 'D': cout << "Poor work !!" << endl; ++numberInTrouble; default: cout << grade << " is not a legal letter" << endl; } cout << "End of grade assignment" << endl;
- To redirect the flow of control outside the switch element, a break statement must be used
switch (grade) { case 'A': cout << "Very good work !!" << endl; break; case 'B': cout << "Good work !!" << endl; break; case 'C': cout << "Average work !!" << endl; break; case 'D': cout << "Poor work !!" << endl; break; case 'F': cout << "Very poor work !!" << endl; break; default: cout << grade << " is not a legal letter" << endl; } cout << "End of grade assignment" << endl;
if(grade == 'A') cout << "Very good work !!" << endl; else if(grade == 'B') cout << "Good work !!" << endl; else if(grade == 'C') cout << "Average work !!" << endl; else if(grade == 'D') cout << "Poor work !!" << endl; else if(grade == 'F') cout << "Very poor work !!" << endl; else cout << grade << " is not a legal letter" << endl; cout << "End of grade assignment" << endl;