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

后端 未结 3 867
时光说笑
时光说笑 2021-01-02 23:08

I have a problem that I can not understand

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


        
相关标签:
3条回答
  • 2021-01-02 23:48

    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.

    0 讨论(0)
  • 2021-01-02 23:48

    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.

    0 讨论(0)
  • 2021-01-03 00:10

    [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.

    0 讨论(0)
提交回复
热议问题