Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a boolean operator in a case statement?

Tags:

objective-c

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.

like image 642
Jab Avatar asked Jan 24 '10 03:01

Jab


People also ask

Can we pass Boolean in switch case?

The expression used in a switch statement must have an integral or boolean expression, or be of a class type in which the class has a single conversion function to an integral or boolean value. If the expression is not passed then the default value is true. You can have any number of case statements within a switch.

How do you use Boolean operators?

Boolean Operators are simple words (AND, OR, NOT or AND NOT) used as conjunctions to combine or exclude keywords in a search, resulting in more focused and productive results. This should save time and effort by eliminating inappropriate hits that must be scanned before discarding.

What is an example of a Boolean statement?

A boolean expression(named for mathematician George Boole) is an expression that evaluates to either true or false. Let's look at some common language examples: • My favorite color is pink. → true • I am afraid of computer programming. → false • This book is a hilarious read.

What are the 3 types of Boolean operations?

They connect your search words together to either narrow or broaden your set of results. The three basic boolean operators are: AND, OR, and NOT.


2 Answers

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.

like image 126
zneak Avatar answered Sep 21 '22 19:09

zneak


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.

like image 40
John Knoeller Avatar answered Sep 20 '22 19:09

John Knoeller