Unsigned int reverse iteration with for loops

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

    I am new to c++, my answer might be realy stupid but, i do this for this kind of reverse loops;

    size_t count = 3;
    size_t newCount = 0;
    if (count > 0)
        for (size_t i = count - 1; i >= newCount; i--)
        {
            //do your work here
    
            //and at the end
            if (i == 0)
                break;
        }
    

    and it works. since "i--" part at the loop executed at the next step, break should work allright. what do you think is this way safe ?

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

    My pattern for this is usually...

    for( unsigned int i_plus_one = n; i_plus_one > 0; --i_plus_one )
    {
        const unsigned int i = i_plus_one - 1;
        // ...
    }
    
    0 讨论(0)
  • 2020-12-07 17:04

    Here is a simple trick to ovoid overflow if i iterates by 1:

    for(unsigned int i = n-1; i+1 >= 1; i--) {;}
    

    If you want i to iterate for more than 1:

    unsigned int d = 2;
    for(unsigned int i = n-1; i+d >= d; i-=d) {;}
    
    0 讨论(0)
  • 2020-12-07 17:06
    for (unsigned int i = 10; i <= 10; --i)
    

    You got it in one.

    I don't want to give your decade old question back to you as an answer, but trying to avoid the underflow is going to obfuscate what you're trying to do ultimately.

    Underflow for an unsigned integer is a well defined behavior that you can depend on, and expect other programmers to understand. Any work-around is going to make the range you're trying to act on harder to parse, and will likely be just as confusing to a beginner while imparting a poor example if they should pick it up as a "lesson" in reverse for loops

    0 讨论(0)
  • 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.

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

    Avoiding underflow

    unsigned int i = n;
    while (i !=0){
    --i;
    ...
    }
    
    0 讨论(0)
提交回复
热议问题