Unsigned integers in C++ for loops

前端 未结 4 1300
情书的邮戳
情书的邮戳 2020-12-14 03:36

I have made some research on Stackoverflow about reverse for loops in C++ that use an unsigned integer instead of a signed one. But I still do NOT understand why there is a

4条回答
  •  一个人的身影
    2020-12-14 04:24

    The problem here is that an unsigned integer is never negative.

    Therefore, the loop-test:

    i >= 0
    

    will always be true. Thus you get an infinite loop.

    When it drops below zero, it wraps around to the largest value unsigned value.
    Thus, you will also be accessing x[i] out-of-bounds.

    This is not a problem for signed integers because it will simply go negative and thus fail i >= 0.

    Thus, if you want to use unsigned integers, you can try one of the following possibilities:

    for (unsigned int i = 9; i-- != 0; )
    

    and

    for (unsigned int i = 9; i != -1; i--)
    

    These two were suggested by GManNickG and AndreyT from the comments.


    And here's my original 3 versions:

    for (unsigned int i = 9; i != (unsigned)0 - 1; i--)
    

    or

    for (unsigned int i = 9; i != ~(unsigned)0; i--)
    

    or

    for (unsigned int i = 9; i != UINT_MAX; i--)
    

提交回复
热议问题