-2

I want to make a switch statement for in my code whose cases go over a wide span of integers (1-15000) split into 3 sections: 1-5000,5001-10000,10001-15000.

I tried it once like this:

switch(number) {
    case 1 ... 1000: (statement here); 

This gave me a syntax error on the "..."- "expected a :".

Then I tried:

switch (number) {
case 1:
case 5000:
    (statement);
    break;

This method did compile but didn't work as intended, wrong answer for the cases which were not explicitly listed.

Couldn't find any other suggestions online. Can anyone help?

Hitopopamus
  • 95
  • 1
  • 8
  • 3
    Short answer: You cannot do it in (standard) C. You have to use `if` – UnholySheep Mar 16 '18 at 15:05
  • Roger that. I'll try, thank you. – Hitopopamus Mar 16 '18 at 15:07
  • https://stackoverflow.com/questions/36748934/how-can-i-use-ranges-in-a-switch-case-statement-in-c – Ben Mar 16 '18 at 15:10
  • This question does actually have a difference to the other questions 'already answered'. In this case the ranges are equally sized. try taking advantage of the inherent floor division like this `switch( (number-1)/5000 ) { case 0: break; case 1: break; case 2: break; default: }` – Michael Feb 28 '20 at 08:06

2 Answers2

7

This is not possible in standard C, although some compilers offer switching on a range as a compiler extension1.

The idiomatic way in your case is to write

if (number < 1){
    // oops
} else if (number <= 5000){
    // ToDo
} else if (number <= 10000){
    // ToDo
} else if (number <= 15000){
    // ToDo
} else {
    // oops
}

Or a very crude way would be to write switch((number - 1) / 5000) which exploits integer division: mapping the cases you need to deal with to 0, 1, and 2.


1 https://gcc.gnu.org/onlinedocs/gcc/Case-Ranges.html

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

As @UnholySheep said in the comments, you cannot do this. Not with standard C. Try using if:

if (my_variable >= minumum_value && my_variable <= maximum_value) {
// Do something
} else {
// Do something else
}
kwyntes
  • 1,045
  • 10
  • 27