for() with 4 arguments to allow postcondition
Michel Colman
michelcolman at mac.com
Fri Jun 22 11:57:06 PDT 2012
> Isn't this what a do-while loop is for, or am I missing
> something?
Well, yes, but then you don't need the regular "for" loop either.
After all, isn't that what a "while" loop is for?
The big advantage of "for" is that you can see at a glance what
the initialisation, condition(s) and increments are. It describes
the whole loop in one statement. That's the only reason why it
was invented in the first place, because the language technically
does not need it. You can even declare the variable right there
so its scope is limited to the loop. With a do-while, you first
initialize the variable before the loop (outside of it), then add
the increment just before the end (many pages later, perhaps),
and the condition at the very end. It's all over the place.
> foreach(i; 0..10)
I know my simple example would be optimized, and can indeed be
written with a foreach as well. But if you use some custom class
as the variable, or a pointer, it won't be. For example, turn i
into a Bigint. Or for an entirely different example:
for (Display * d = firstDisplay; d != 0; d = nextDisplay)
if you have already established that at least one display is
present.
Or even simpler:
for (int i = 1; i <= 0x10000000; i <<= 1)
I bet this won't be optimized on many compilers.
And all it would take is one extra semicolon:
for (Display * d = firstDisplay; ; d != 0; d = nextDisplay)
for (int i = 1; ; i <= 0x10000000; i <<= 1)
to tell the compiler to skip the condition before the first
iteration.
> for(initializer;;increment){
> if(!condition1) break;
> body;
> if(!condition2) break;
>}
Yes, that's exactly what I meant.
Michel
More information about the Digitalmars-d
mailing list