Controlling Program Flow: Multiple Identical Options in switch Statements

What is it?

C++ Multiple Identical Options in switch Statements is a feature of the switch statement that allows multiple cases to execute the same code block or statement. This is useful when multiple cases need to perform the same action.


Syntax

The syntax for using multiple identical options in a switch statement is:

switch (expression) {
    case value1:
    case value2:
    case value3:
        //code to be executed for value1, value2, or value3
        break;
    case value4:
        //code to be executed for value4
        break;
    default:
        //code to be executed if expression doesn't match any case
        break;
}

Where,

  • expression: An expression that evaluates to an integral type or an enumeration.
  • value1, value2, value3, value4, etc.: The possible values of the expression to evaluate.



How to use it

To use multiple identical options in a switch statement, follow the below steps:

  1. Define a switch statement with the expression to evaluate.
  2. Define case statements for each possible value of the expression.
  3. For values that should execute the same code block, list them one after another, separated only by a colon (:).
  4. At the end of each code block, include a break statement to exit the switch statement.
  5. Optionally, include a default case to handle any values that do not match any case.



Program code snippet example

#include <iostream>
using namespace std;

int main() {
    int day = 3;

    switch (day) {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
            cout << "Weekday" << endl;
            break;
        case 6:
        case 7:
            cout << "Weekend" << endl;
            break;
        default:
            cout << "Invalid day" << endl;
            break;
    }

    return 0;
}

Output:

Weekday

In the above example, the case statements for values 1 to 5 execute the same code block, which outputs "Weekday". Similarly, the case statements for values 6 and 7 execute the same code block, which outputs "Weekend".




Write a switch statement which tests val and set answer to the following ranges:

  • 1-3 - "Low"
  • 4-6 - "Mid"
  • 7-9 - "High"