Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression in FOR command (for (int i=0; i < ([arr count]-1);i++){})

I have a problem that I can not understand

NSArray *emptyArr = @[];
for (int i=0; i < ([emptyArr count]-1) ; i++) {
    NSLog(@"Did run for1");
}

[emptyArr count] - 1 is -1 but my app still runs NSLog command!

If I use a int variable:

NSArray *emptyArr = @[];
int count = [emptyArr count]-1;
for (int i=0; i < count ; i++) {
    NSLog(@"Did run for1");
}

then my app doesn't run NSLog command.

Anyone help me please!

like image 442
Tony Avatar asked Jun 11 '13 08:06

Tony


1 Answers

This is because the return type of count is an unsigned int. When you substract 1 from 0, you do not get -1. Instead you underflow to the highest possible unsigned int. The reason it works in the second version is because you cast it (implicitly) to an int in which the value -1 is legal.

like image 125
borrrden Avatar answered Oct 05 '22 18:10

borrrden