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

Timon Gehr timon.gehr at gmx.ch
Wed Aug 24 12:04:50 PDT 2011


On 08/24/2011 08:04 PM, Andrej Mitrovic wrote:
> Here's some code that iterates through "parents" of some class object
> until it finds an object with no parent (where parent is null):
>
> import std.stdio;
>
> class Foo
> {
>      Foo parent;
>      int state;
>
>      this (int state) { this.state = state; }
> }
>
> void main()
> {
>      auto foo          = new Foo(0);
>      foo.parent        = new Foo(1);
>      foo.parent.parent = new Foo(2);
>
>      while (true)
>      {
>          if (auto par = foo.parent)
>          {
>              writeln(par.state);
>              foo = par;
>          }
>          else
>          {
>              break;
>          }
>      }
> }
>
> (syntax-highlighted: http://codepad.org/8yHRmICh)
>
> But I was hoping I could simplify this by doing:
>
>      while (auto par = foo.parent)
>      {
>          writeln(par.state);
>          foo = par;
>      }
>
> However that doesn't work, I get back:
> expression expected, not 'auto'
>
> Is there a limitation on why this couldn't work or can this be added
> to the language?

Afaics, this could be added just like it could be added for if. In fact 
the compiler should be able to simply rewrite it to your first example.
I think it is worth an enhancement request, because there are situations 
where this would be useful, and implementation should be trivial, if 
somebody has the time. (I also think it adds to the consistency of the 
language, but others may disagree.)


(btw, i always use for(;;) instead of while(true), it is usually faster 
in debug mode and faster to type :))


More information about the Digitalmars-d-learn mailing list