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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With