4

I've got a problem where I want to do one of three things... if the value of x is 1-5 (inclusive) do A, if x is between 6-13 (inclusive) do B, and if x is between 14-16 do C.

I figured the switch case would be ok, although I guess I could use a plain IF / ELSE IF, however, as I coded it, I can't help but think there is a more elegant way of stating this USING the switch/case (just in case I encounter a similar need that has more then three options).

here is what I have:

switch ( x ) {
    case 1:case 2:case 3:case 4:case 5:
        // DO A
        break;
    case 6:case 7:case 8:case 9:case 10:case 11:case 12:case 13:
        // DO B
        break;
    case 14:case 15:case 16:
        // DO C
        break;
}

is there a way in the case to specify "between" (inclusive or exclusive)?

thanks

j-p
  • 3,698
  • 9
  • 50
  • 93

1 Answers1

6

Nope. Switch statement are designed to work with single, constant values. Unless the comparison is such that the value can be modified to conform to that rule, the only options are what you have written already OR using if/else if/else, AFAIK. In most cases, the latter is cleaner than a bunch of hard coded case statements IMO.

Community
  • 1
  • 1
Leigh
  • 28,765
  • 10
  • 55
  • 103
  • Ya, as I figured, after thinking about it - with 3 options, it'd be cleaner to do IF ( x >= 1 && x <=5 )... in THIS instance... I just needed to know for future reference. thx – j-p Aug 10 '15 at 05:30
  • Yep. My approach is go with whichever one makes the intent of the expression more clear. For ranges, and other complex comparisons, that usually means `if/elseif`. – Leigh Aug 10 '15 at 17:01