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

I have a problem that I do not understand

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

[emptyArr count] - 1 - -1, but my application still runs the NSLog command!

If I use the int variable:

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

then my application does not run the NSLog command.

Someone help me!

+6
source share
3 answers

This is because the return type of count is unsigned int . When you set 1 out of 0, you don't get -1. Instead, you go to the highest possible unsigned int . The reason it works in the second version is because you (implicitly) apply it to an int , in which the value -1 is legal.

+6
source

[emptyArr count]-1 never less than 0, as it is unsigned. I assume that if you do ((int)[emptyArr count]-1) , you will get the correct behavior.

0
source

The value returned by [emptyArr count] is an unsigned integer. In the first case, [emptyArr count] -1 - 0-1, presented in 2 compliments, which is a huge number. Therefore, he prints a magazine many times.

In the second case, [emptyArr count] -1 → You make the result of this in int. 0-1 → -1, signed int. Therefore, does not print.

0
source

Source: https://habr.com/ru/post/947012/


All Articles