Unsigned int reverse iteration with for loops

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

    I would use two variables:

    unsigned int start = 10;
    for (unsigned int j = 0, i = start; j <= start; ++ j, -- i) {
        // ...
    }
    

    You can also use a while loop:

    unsigned int start = 10;
    unsigned int i = start + 1;
    while (i --) {
        // ...
    }
    
    0 讨论(0)
  • 2020-12-07 17:10

    One more way:

    for(unsigned i = n-1; i < n ; --i) 
    {       
        // Iterates from n-1 to 0
    }
    

    Simillarly for size_t (unsigned integer type) use the same trick

    for(std::size_t i = n-1; i < n ; --i) 
    {       
        // Iterates from n-1 to 0
    }
    
    0 讨论(0)
  • 2020-12-07 17:12

    You can use

    for( unsigned int j = n; j-- > 0; ) { /*...*/ }
    

    It iterates from n-1 down to 0.

    0 讨论(0)
  • 2020-12-07 17:13

    Just:

    int start = 10;
    for(unsigned int iPlus1 = start + 1 ; iPlus1 > 0 ; iPlus1--) {
      // use iPlus1 - 1 if you need (say) an array index
      a[iPlus1 - 1] = 123; // ...
    }
    

    No?

    0 讨论(0)
  • 2020-12-07 17:15
    for(unsigned i = x ; i != 0 ; i--){ ...
    

    And if you want to execute the loop body when i == 0 and stop after that. Just start with i = x+1;

    BTW, why i must be unsigned ?

    0 讨论(0)
  • 2020-12-07 17:20

    The following does what you want:

    for (unsigned i = 10; i != static_cast<unsigned>(-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

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