0

I've an if statement, used to check if an indice is less than the end of the array. This is not working when the value of "i" is -1.

NSMutableArray *myArray = [NSMutableArray array];
[myArray addObject:@"coucou"];

int i = -1;

// Not working
if (i < ([myArray count] - 1) ){
    NSLog(@" first ok ");
}

// Fix
int count = [myArray count] - 1;
if ( i < count ){
    NSLog(@" second ok ");
}

This is what i need to do to get it working (same algorithm, but using an intermediate variable to store the size of the array) Anyone know why ?

Hacketo
  • 4,978
  • 4
  • 19
  • 34
  • 3
    because [myArray count] returns NSUInteger and you are compairing it with int variable. use (int)[myArray count]. It will work fine. – Yogendra Jul 01 '14 at 09:31

3 Answers3

3

[myArray count] return a NSUInteger which is an unsigned integer value.

When you compare an unsigned integer with an signed integer, the signed integer will be convert to unsigned, so the value i is not negative now.

Look here for more information.

Community
  • 1
  • 1
KudoCC
  • 6,912
  • 1
  • 24
  • 53
  • Yeah much closer to the truth. You should emphasize that by "not negative" you actually get "very large" during such conversions. – trojanfoe Jul 01 '14 at 09:41
  • Unsigned value is the 2's complement of the signed value. That's why for negative values it results in very large/small number like this: (2^32 - abs(your number)). The number of bits are machine architecture dependent. If your integer carries 4 byte then its 32 bit etc. – if-else-switch Jul 01 '14 at 09:50
0

You are comparing a signed integer with int thats why it is happening use NSUInteger instead of int. It will definitely work

Avinash Tag
  • 162
  • 2
  • 12
  • 1
    because when you are writing `if (i < ([myArray count] - 1) ){ NSLog(@" first ok "); } `([myArray count] - 1) gives you and unsigned integer and you are comparing it with int use expression [myArray count]-1 to debug you will get your answer – Avinash Tag Jul 01 '14 at 09:46
0

[myArray count] it returns unsigned long value you need to keep either of these two

((NSInteger)[myArray count] - 1) OR ((int)[myArray count] - 1)
Balu
  • 8,470
  • 2
  • 24
  • 41