Unsigned int reverse iteration with for loops

后端 未结 14 1124
离开以前
离开以前 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:20

    The following does what you want:

    for (unsigned i = 10; i != static_cast(-1); --i)
    {
        // ...
    }
    

    This is perfectly defined and actually works. Arithmetic on signed types is accurately defined by the standard. Indeed:

    From 4.7/2 (regarding casting to an unsigned type):

    If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n where n is the number of bits used to represent the unsigned type)

    and 3.9.1/4

    Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2^n where n is the number of bits in the value representation of that particular size of integer

提交回复
热议问题