0

I want to use logical operators in switch statment.
For Example:
" x is greater than 3 and is less than 7 "
Using it in If statement.

if(x > 3 && x < 7)
  {
    //something
  }else if(x 11 3 && x < 15){
         // anything
  }

How can I use it in switch statement.
And how to use arithmetic operators.
UPDATE
Now how we use it in switch. Can there is not way to use it in switch.

Axeem
  • 670
  • 4
  • 16
  • 26

1 Answers1

2

You mean, something like this?

switch (some_var)
{ case 4 : // fall through
  case 5 : // fall through
  case 6 : do_something();
          break;
  default : do_something_else();
           break;
}

It's ugly, and gets worse the larger a range you want to cover, but since switch cases must be constants, that's one way to do it.

Another way would be:

switch ((some_var > 3) && (some_var < 7))
{ case 0: do_something_else(); break;
  default: do_something(); break;
}

But that'll only work if you have exactly one range you want to test. There are other ways if you have a set of equally-sized intervals that are spaced equally far apart, using some basic arithmetic, but we'd have to know a bit more about the specific problem(s) you're trying to solve...

Frankly, though, I think the if construct is the better solution...

twalberg
  • 59,951
  • 11
  • 89
  • 84