for() with 4 arguments to allow postcondition
Timon Gehr
timon.gehr at gmx.ch
Tue Jun 19 04:22:54 PDT 2012
On 06/19/2012 12:51 PM, Michel Colman wrote:
> I have a suggestion for D (which might make it into C/C++ as
> well, but I thought D would be a more accessible place to suggest
> it):
>
> for(initializer; precondition; postcondition; increment)
>
> would allow avoiding a useless comparison before the start of the
> first iteration of a "for" loop in those cases where the
> programmer knows the loop will always iterate at least once. This
> new 4-argument version could exist alongside the old 3-argument
> version. An extra semicolon is all it would take to turn a
> precondition into a postcondition.
>
> So now you could still write:
>
> for (i = 0; i < 10; ++i) // old syntax still available,
> *hopefully* optimized by compiler
>
foreach(i; 0..10)
> but you could just add an extra semicolon to explicitly avoid
> comparing 0 to 10:
>
> for (i = 0; ; i < 10; ++i) // new syntax avoids comparing 0 to 10
>
> Of course in this simple case, the compiler will probably
> optimize the loop anyway so there will be no difference in the
> resulting code (at least if "i" is an int), but replace 10 by a
> variable which you know to be greater than 0, or use a custom
> class for the iterator, or replace the comparison with a function
> call, and the only way to avoid checking the condition before the
> first iteration is by using "do while()" which is less readable.
>
> Obviously, using both a precondition AND a postcondition would
> not be recommended for readability although it would be legal and
> might be useful in obfuscation contests.
>
> Feel free to grab this idea and propagate it to wherever you
> like. I would love to see this feature turn up in D and maybe
> in C and C++ as well.
You have missed to describe the exact semantics of the construct.
Should it be like this?
for(initializer; condition1; condition2; increment)
=>
for(initializer;;increment){
if(!condition1) break;
body;
if(!condition2) break;
}
> And it seems very easy to implement.
>
It is. But in ~16'000 LOC, I have used 56 'for' statements. 3 of them
have the property that they always execute the first loop iteration and
this is not immediately obvious to the compiler.
Therefore, I think the proposed syntax sugar is useless.
More information about the Digitalmars-d
mailing list