tags:

views:

85

answers:

2

I just Don't understand how to use a boolean operator inside a switch statement

switch (expression) {
        case > 20:
            statements
            break;
        case < -20:
            statements
            break;
    }

Edit:
I don't want an If () statement.

+5  A: 

You can't. Use if() ... else ....

The nearest thing available to what you want uses a GCC extension and is thus non-standard. You can define ranges in case statements instead of just a value:

switch(foo)
{
    case 0 ... 20: // matches when foo is inclusively comprised within 0 and 20
         // do cool stuff
         break;
}

However, you can't use that to match anything under a certain value. It has to be in a precise range. Switches can only be used to replace the comparison operator against a constant, and can't be used for anything more than that.

zneak
Unfortunately, speed comes at the cost of flexibility, and there's no way around using a boolean operator instead a switch. It's faster because the CPU has less work to do on it. If you could use a boolean operator inside a `switch`, there would be no reason `if` statements would be any slower than `switch` statements.
zneak
What happens when I have more than like 5 cases though?
Jaba
Well, it's just my rule of the thumb, and I didn't mean to make it look like such an absolute rule. You do whatever you like in that case. I'm going to edit that.
zneak
Then you use the 'else if' statement to handle them. As others have said, 'switch' is for situations with known result values.
Nicholas
+1  A: 
switch ((expression) > 20) {
        case true:
            statements
            break;
        case false:
        default:
            statements
            break;
    }

What.. you want more than 1 boolean in a case? You could do this

int ii = ((expression) > 20) + 2 * ((expression) < -20);
switch (ii) {
        case 1:
            statements
            break;
        case 2:
            statements
            break;
    }

This, IMO is pretty bad code, but it is what you asked for...

Just use the if statement, you'll be better off in the long run.

John Knoeller
I'd like to remind that it's mostly the comparison that makes `if` slower than `switch`es, and consequently this won't help your code go faster.
zneak
actually that's not true. it's the BRANCH that causes the slowdown, not the comparison. But a switch is still a branch.
John Knoeller