for() with 4 arguments to allow postcondition

Michel Colman michelcolman at mac.com
Tue Jun 19 03:51:10 PDT 2012


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

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. And it seems very easy to implement.



More information about the Digitalmars-d mailing list