Chev Chev - 1 year ago 127
Objective-C Question

Objective-C: How to check a number is between two values

Going a little nuts here with a super noob issue. How do a check if and int is between two values i.e. want to see if x<100 && x>50 I have tried:

if(x<100 && x>50){

but not having any joy??

Joe Joe
Answer Source

Unless your compiler is broken there is nothing wrong with that code. There is probably something wrong with x

As Sascha stated in the comments make sure that x is not an NSNumber. The reason for this is if x is an NSNumber then the value stored in it is a pointer which value would likely be much higher than 100 (0x4FBC60 for example) and you would want to compare against the -(int)intValue.

Other things to consider are comparing against the right data. While implicit number conversions work well you may want to use the same literal comparison as your data type.

unsigned long long x = 51ull;
if(x > 50ull && x < 100ull)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download