Why no (auto foo = bar) in while loops?

Ali Çehreli acehreli at yahoo.com
Thu Aug 25 17:00:36 PDT 2011


On Thu, 25 Aug 2011 23:31:26 +0200, Timon Gehr wrote:

> for(init; condition; statement){}
> while(    condition           ){}

That's a very interesting way of looking at the question.

I bet that explains the other way around: there can't be a variable 
definition in the 'for' loop's condition clause, because 'while' doesn't 
allow it. :p

The compiler probably uses 'while's implementation. The 'for' loop 
probably becomes this:

{
    for_init;
    while (for_condition) {
        for_body;
        for_statement;
    }
}

So there is no discrepancy: the condition clauses cannot define a 
variable in either loop. :)

If 'while' gets this enhancement, 'for' could be written as the following:

for (int i = 0; auto c = condition(); ++i) {

    // Yes, we know that c doesn't evaluate to 'false', but
    // we can use c here when it evaluates to 'true'.
    // e.g. if it's a pointer:

    writeln(*c);
}

Ali


More information about the Digitalmars-d-learn mailing list