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

Mafi mafi at example.org
Wed Aug 24 15:47:34 PDT 2011


Am 24.08.2011 21:04, schrieb Timon Gehr:
> 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 :))

I just have to say that it already works for 'if'. It's a great feature 
because in the body of the 'if' you know the value is non-null and 
outside,  where there could be an segfault, the variable is not visible.
I'm not really sure if it's good for 'while'.
I'm unsure because there are two somewhat natural semantics for such a 
construct.

//example
//more to the nature of while
while(auto obj = init) { work(obj); }

//1 (your interpretation)
typeof(init) obj;
while(obj = init) { work(obj); }

//2
/*
seems more natural for me because init runs only once (like any other 
init and like in 'for' or 'if')
*/
auto obj = init;
while(obj) { work(obj); }

This could confuse many people, I think. What do you think?

Mafi



More information about the Digitalmars-d-learn mailing list