C++ – Counting down in for-loops

c++for-loop

I believe (from some research reading) that counting down in for-loops is actually more efficient and faster in runtime. My full software code is C++

I currently have this:

for (i=0; i<domain; ++i) {

my 'i' is unsigned resgister int,
also 'domain' is unsigned int

in the for-loop i is used for going through an array, e.g.

array[i] = do stuff

converting this to count down messes up the expected/correct output of my routine.

I can imagine the answer being quite trivial, but I can't get my head round it.

UPDATE: 'do stuff' does not depend on previous or later iteration. The calculations within the for-loop are independant for that iteration of i. (I hope that makes sense).

UPDATE: To achieve a runtime speedup with my for-loop, do I count down and if so remove the unsigned part when delcaring my int, or what other method?

Please help.

Best Solution

There is only one correct method of looping backwards using an unsigned counter:

for( i = n; i-- > 0; )
{
    // Use i as normal here
}

There's a trick here, for the last loop iteration you will have i = 1 at the top of the loop, i-- > 0 passes because 1 > 0, then i = 0 in the loop body. On the next iteration i-- > 0 fails because i == 0, so it doesn't matter that the postfix decrement rolled over the counter.

Very non obvious I know.