+ 1
Switch range
Can we include ranges in switch cases ? If yes what is the syntax ?
2 Réponses
+ 5
It's not standard C++, but some compilers allow it as an extension. The syntax is
case lower ... upper:
where "lower" and "upper" are both included in the range.
Keep in mind this is not standard, so if portability is a factor, you should probably not include it in your code.
+ 4
It does work here in the SoloLearn playground, FYI. Here's an example.
https://www.google.com/amp/s/www.geeksforgeeks.org/using-range-switch-case-cc/amp/
https://code.sololearn.com/cIQm1QkSgElw/?ref=app
For more portability you can take advantage of the switch case fallthrough and list multiple cases consecutively without using a break statement for those ranges. Although this can become cumbersome if you have a large range.