With a for
loop you can move the post-statement empty and move it to the bottom of the code in the loop:
for (int i = 0; i < 10; /* empty */ ) {
//...
++i;
}
But in this case it doesn't gain you anything; more importantly it makes the code harder to read as you would expect the ++i
to reside at the top of the statement as the post-statement.
So when is it valid to move the post-statement from its usual location to somewhere inside the loop?
EDIT: The code which made me think about this question I got from C++ Primer:
for (T* p = first_free; p != elements; /* empty */)
alloc.destroy(--p);
Here first_free
is a pointer to the first free element in an array of objects to be destroyed in reverse order, and elements
is a pointer to the first object in the array. Here it seems, to me, valid to move --p
from a post-statement into the loop, because otherwise you would need to rewrite the code as such:
for (T* p = first_free - 1; p != elements; --p)
alloc.destroy(p);
Here the code would run into problems if the array doesn't actually contain any objects as you would skip over elements
and thus cause a crash (or at least undefined behaviour). This means you would need an additional check before the loop whether the array actually contains any elements or not.
for
loops when the number of iterations is not known before looping always makes me cringe. After all, that's whatwhile
loops were designed for. Semantics do matter, IMHO. – Schedler Apr 25 '11 at 11:16