I have a problem that I can not understand
NSArray *emptyArr = @[];
for (int i=0; i < ([emptyArr count]-1) ; i++) {
NSLog(@\"Did run for1\");
}
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.
The value returned by [emptyArr count] is unsigned integer. In the first case, [emptyArr count]-1 is 0-1 represented in 2's compliment, which is a huge number. So it prints the log many times.
In the second case, [emptyArr count]-1 -> You are casting the result of this to int. 0-1 -> -1 signed int. Hence does not print.
[emptyArr count]-1
is never less than 0 since it is unsigned. I'm guessing if you do ((int)[emptyArr count]-1)
, you will get the correct behavior.