Rewrite if/else statement into switch statement?

How do I rewrite the following into switch statements? Do I have to define those conditions in the if parentheses?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int x = 0;
       int i = 1, j = 2, k = 3, m = 4, n = 5;
      
       if (x > 15 && x <= 19) {
              i += 1;
       } else if (x == 21) {
              j += 2;
              n = 8;
       } else if (x > 21 && x < 23) {
              k *= 3;
       } else {
              m += k + 5;
       }
 
switches are based off a single integer value.

you have to boil it down to use one.
you can do a

case(16):
case(17):
...
case(19):
... stuff

case(21):
otherstuff

type setup.


you can also do a lookup table approach:

int lut[24] = {0}; //an enum to name what the cases mean might be useful here.
lut[16] = 1;
lut[17] = 1;
..
lut[21] = 2;
...

etc then
get all clunky..
unsigned int sw = 5;
if sw < 24
sw = lut[sw];
switch(sw)
case 0:
..
case 1:
...

Last edited on
just what i was looking for, thank you jonnin :) !
jonnin wrote:
case(16): case(17): ... case(19): ... stuff case(21):

Hi, jonnin. Sorry, beginner question: is there a specific reason for adding parentheses around the numbers in ‘case’ statements or is just something to improve readability or similar?
just from habit. There is no good reason for it. I won't even pretend it adds any readability.

Last edited on
Thank you.
Topic archived. No new replies allowed.