Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch-Case Statement and Range of Numbers

Tags:

objective-c

Is there a way to use switch statement with ranges in Objective C (in XCode), hypothetically something like this:

- (NSString *)evaluate:(NSInteger)sampleSize
{
       NSString returnStr;
       switch (sampleSize)
           {
               case sampleSize < 10: 
               returnStr = @"too small!";
               break;

               case sampleSize >11 && sampleSize <50:
               returnStr = @"appropriate";
               break;

               case sampleSize >50:
               returnStr = @"too big!";
               break;
           }
       return returnStr;
}
like image 908
Canopus Avatar asked Nov 18 '11 00:11

Canopus


People also ask

Can switch case be used for range?

Using range in switch case in C/C++ You all are familiar with switch case in C/C++, but did you know you can use range of numbers instead of a single number or character in case statement.

How do you use range of values in a switch case?

Using range in switch case in C/C++ In the switch statement we pass some value, and using different cases, we can check the value. Here we will see that we can use ranges in the case statement. After writing case, we have to put lower value, then one space, then three dots, then another space, and the higher value.

Can we test range 5 to 7 or 8 to 10 using a switch statement in C programming?

Can we test range 5 to 7 or 8 to 10 using a switch statement in C Programming ? A char variable storing either an ASCII character or a Unicode character is allowed inside switch case. We cannot use String in the Switch case as label !

Does switch case work with integers?

Important points to C Switch Case Only Integral values are allowed inside the case label, and the expression inside the switch must evaluate to a single integral constant. Variables are not allowed inside the case label, but integer/character variables are allowed for switch expression. Break and default are optional.


1 Answers

There is a GCC extension (which I assume is supported in Clang) that might be suitable for you. It allows you to use ranges in case statements. The full documentation is at http://gcc.gnu.org/onlinedocs/gcc-4.2.4/gcc/Case-Ranges.html#Case-Ranges - an example case statement from that page is

case 1 ... 5:

which would match (unsurprisingly) 1, 2, 3, 4, or 5.

like image 127
Hugh Avatar answered Oct 16 '22 03:10

Hugh