Unsigned int reverse iteration with for loops

后端 未结 14 1123
离开以前
离开以前 2020-12-07 17:00

I want the iterator variable in a for loop to reverse iterate to 0 as an unsigned int, and I cannot think of a similar comparison to i > -1, as

14条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-07 17:09

    I can think the two options are either cast or singed numbers (can be done implicitly be comparing to -1, for example) or use the loop condition to check for overflow like this:

    for(unsigned i=10;i>i-1;--i){ } // i = 10, 9, ... , 1
    for(unsigned i=10;i+1>i;--i){ } // i = 10, 9, ... , 1,0
    

    This loop will continue until i overflows (meaning that it reached zero). Note that is important that i iterates by 1, or you might end-up with an infinite loop.

提交回复
热议问题