Why no (auto foo = bar) in while loops?
Steven Schveighoffer
schveiguy at yahoo.com
Thu Aug 25 08:31:56 PDT 2011
On Thu, 25 Aug 2011 11:15:44 -0400, Jonathan M Davis <jmdavisProg at gmx.com>
wrote:
> On Thursday, August 25, 2011 07:11:31 Steven Schveighoffer wrote:
>> > On 08/25/2011 12:47 AM, Mafi wrote:
>> >> 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')
>> >> */
>> >
>> I'd say just leave the auto x = y for if and for loops, where there is a
>> clear "run once" section.
>>
>> Also, what do you do with a do while loop if the while contains this
>> construct?
>>
>> I just find the whole thing confusing.
>
> I don't see why it would be confusing. Because it's unclear whether it's
> set
> every time or whether it's a new variable every time? It's actually one
> of
> those things that I do periodically thinking that it works and then get
> frustrated when it doesn't, so I'd love to see it added.
See Mafi's response above.
What it boils down to is, I usually replace code like this:
auto x = condition;
if(x)
{
// use x
}
with this:
if(auto x = condition)
{
// use x.
}
so the logical mapping to while would map this:
auto x = condition;
while(x)
{
// use x.
}
to this:
while(auto x = condition)
{
// use x.
}
But it looks like every time through the loop x gets reassigned to
condition. That's not what I'd want. At the very least, it's confusing
semantics one way or the other.
If you use the construct in the *init* section of a for loop, it reads the
same as the if statement, since that part is only executed once.
The while loop just doesn't fit the model.
-Steve
More information about the Digitalmars-d-learn
mailing list