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.

5
  • What language is this? JavaScript? C#? Java? C? Commented Nov 12, 2013 at 17:47
  • 2
    I believe case: expressions have to be constant. So, the correct way is to use the if statement. Commented Nov 12, 2013 at 18:08
  • My question is that can we use expression in switch or not. if yes then how??? Commented Nov 12, 2013 at 18:19
  • 1
    Whatever book you're using to learn C++ isn't doing a very good job. switch accepts an expression. case does not. Commented Nov 12, 2013 at 20:35
  • 2
    @RaymondChen Actually, just to clarify that a bit - case can accept an expression, as long as it's a constant expression that is fully defined and computable at compile time... Commented Nov 12, 2013 at 21:21

1 Answer 1

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...

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.