1

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.

Anthony
  • 81
  • 7
  • Advice -- do not use another computer language as a guide in writing C++ code. If you go down that road of trying to make C++ look like your other favorite computer language, you will wind up with buggy code, inefficient programs, or code that looks plain weird to a C++ programmer. – PaulMcKenzie Aug 04 '20 at 15:23
  • To be honest, any decent book, tutorial or class should have taught you how to do this. – Some programmer dude Aug 04 '20 at 15:24
  • I have found that there is a lot of syntax in other languages that doesn't work in C++. – Eljay Aug 04 '20 at 15:25

4 Answers4

6

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.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
5

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.

cigien
  • 57,834
  • 11
  • 73
  • 112
2

You can't do a range of values, but you can do multiple values:

switch (input) {
    case 1:
        cout << "option 1 \n";
        break;
    case 2: case 3: case 4:
        cout << "option 2 or 3 or 4\n";
        break;
    
    default:
        break;
}
Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234
0

You need to use spaces between them with three(...)

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;
}
Aayush Mall
  • 963
  • 8
  • 20