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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With