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

Timon Gehr timon.gehr at gmx.ch
Thu Aug 25 17:55:05 PDT 2011


On 08/26/2011 02:00 AM, Ali Çehreli wrote:
> 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. :)

There is a little discrepancy because 'if' condition clauses can. ;)

>
> 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);
> }
>

Only if it is specifically enabled. The compiler can only rewrite it to 
the while form if it can successfully parse it. But I think that indeed 
iff while is enhanced, for should be too.



More information about the Digitalmars-d-learn mailing list