Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you accept multiple values for a switch case? [duplicate]

How does one accept more than one value for a single case in C++? I know you can make a range of values for one case (e.g. case 1..2) in some other languages, but it doesn't seem to be working in C++ on Xcode.

int main() {
    int input;
    cin >> input;
    switch (input) {
        case 1:
            cout << "option 1 \n";
            break;
        case 2..3: //This is where the error occurs
            cout << "option 2 and 3 \n";
            break;
        
        default:
            break;
    }
    return 0;
}

The program shows an error saying "Invalid suffix '.3' on floating constant" where the range is.

like image 288
Anthony Avatar asked Aug 10 '26 14:08

Anthony


2 Answers

You can "fall through" by having sequential case statements without a break between them.

switch (input) {
    case 1:
        cout << "option 1 \n";
        break;
    case 2:
    case 3:
        cout << "option 2 and 3 \n";
        break;
    
    default:
        break;
}

Note that some compilers support range syntax like case 50 ... 100 but this is non-standard C++ and will likely not work on other compilers.

like image 55
Cory Kramer Avatar answered Aug 13 '26 04:08

Cory Kramer


You could simply do:

switch (input) {
        case 1:
            cout << "option 1 \n";
            break;
        case 2: [[fallthrough]]
        case 3:
            cout << "option 2 and 3 \n";
            break;
        default:
            break;
    }

Note that case 2 ... 3 is called case ranges, and is a non-standard gcc extension that you could use.

like image 39
cigien Avatar answered Aug 13 '26 04:08

cigien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!