NSUInteger in reversed loop confusion?

后端 未结 2 526
野性不改
野性不改 2021-01-28 03:59

I wonder if someone can explain something, I setup a loop where I wanted to count backwards from 10 to 0 :

for(NSUInteger index = 10; index >= 0; index--) {
          


        
相关标签:
2条回答
  • 2021-01-28 04:10

    Note that an NSUInteger is always >= 0, by consequence, your loop condition will always be true.

    0 讨论(0)
  • 2021-01-28 04:32

    An unsigned type can't "keep going into negative numbers". After the iteration when index = 0, index-- becomes 0xFFFFFFFF, which is still more than zero. Easy mistake to make, I've done it myself.

    The static analyzer will actually warn you about this ("Condition index >= 0 is always true" or such like.) I highly recommend setting it to run automatically on debug builds.

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