for() with 4 arguments to allow postcondition

Timon Gehr timon.gehr at gmx.ch
Fri Jun 22 13:07:32 PDT 2012


On 06/22/2012 08:57 PM, Michel Colman wrote:
>> 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.

foreach-range works with custom types.

> 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.
>

If firstDisplay is trivially non-null, the compiler will remove the 
comparison. Furthermore, the additional comparison is extremely cheap 
and will likely be completely unnoticeable.


> Or even simpler:
>
> for (int i = 1; i <= 0x10000000; i <<= 1)
>
> I bet this won't be optimized on many compilers.
>

I bet this is optimized on any halfway decent optimizing compiler. This
is the kind of simple optimization compilers are good at.

> 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.
>

The examples do not make a compelling case.


More information about the Digitalmars-d mailing list