switch case statement: use ranges? (case 0 to 10:)

hi!

In Visual Basic, when using a switch case statement, I can not only specify certain values, but also ranges for the analyzed value. e.g.

switch(x)
{
case 0 to 10: foo(); break;
case 11 to 20: bla(); break;
}

So far, I haven't been able to do that with the Arduino. Is there a way to achieve this without resorting to normal if statements?

switch (x) {

case 0:
case 1:
case 2:
case 3: zero_to_three_action (); 
            break;

case 4:
case 5:
case 6:
case 7: four_to_seven_action ();
            break;
}

Is probably the best you'll manage.

if (x>=0 && x<=10){
  foo();
} else if (x>=11 && x<=20){
  bla();
}

@AWOL: That's actually a nice trick. however, I need to evaluate angles from -179 to 180 degrees, so that would make a REALLY long program :slight_smile: I might remember it for other uses though.

@AlphaBeta: Yeah, I guess thats what I'll be facing.

But I guess since I want to split up the angles into eight equal pieces (basically the directions up, up-right, right, down-right, etc), I can simply divide them by 45 and then use a switch case statement without much hassle :sunglasses:

maybe you can make use of the map function?

y = map(x,-179,180,1,8);
switch(y)
{
case 1 : ....; break;
case 2 : ....; break;
case 3 : ....; break;
.
.
.
.
case 8 : ....; break;
}

cheers
Peter

Good idea!
Meanwhile, I had written my own function to do it:

      dir=(int)(deg+180+22.5)/(int)45;
      if(dir==8) dir=0;

(in case anyone's interested:)
the +180 is to get 1 to 360 instead of -179 to 180.
the +22.5 degree shifts it again because e.g. I want the direction 4 (right) to span 22.5 degrees up and down starting from the horizontal axis.
this way, direction 0 is left, 1 is down-left, 2 is down, ... and 7 is up-left

This works . . .

    switch (x) {
    case 1 ... 8:                       // digits 0-8 (0 & 9 not used)
      // stuff
     break;
     }

Not ANSI but works with Arduino. Haven't tried it with larger ranges.