to auto or not to auto ( in foreach )

cym13 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jul 16 14:39:42 PDT 2016


On Saturday, 16 July 2016 at 20:00:39 UTC, Seb wrote:
> On Saturday, 16 July 2016 at 14:11:34 UTC, cym13 wrote:
>> On Saturday, 16 July 2016 at 14:00:56 UTC, dom wrote:
>>> foreach(auto v; msg)
>>>   writeln(v);
>>>
>>> gives an error that a basic type is expected
>>>
>>> foreach(v; msg)
>>>   writeln(v);
>>>
>>> works
>>>
>>> .. but why?
>>
>> Arbitrary limitation. If you want to say how surprising and 
>> uselessly limiting it is wait at the end of the line.
>>
>> It's not actually a problem in practice because you just have 
>> not to put it but it is part of those frustrating little edge 
>> cases with no reason to be.
>
> It's not arbitrary. It keeps the language simple and easy to 
> read. After all the entire auto keyword is just there, because 
> the compiler needs a keyword and in loops it's clearly defined 
> what the type will be.
> You don't complain that `int int` is forbidden, or do you?
>
> I guess you are frustrated because you are used to this pattern 
> from other, inferior languages. I bet you will soon start to 
> appreciate the syntactic sugar that D provides.

int int is a completely different issue, and that has nothing to 
do with what you suppose my experience is from other languages. 
If anything I come mainly from python so I find not having to 
write the type a pretty thing.

However auto should be allowed here. You are defining a variable 
and the fact that it's in a foreach shouldn't be of any 
importance. The language should enforce orthogonality of 
orthogonal things, not break it. A variable definition in a 
foreach should be allowed not because I like to be pedantic but 
because it's allowed everywhere else. That also stands for the 
principle of least surprise.


More information about the Digitalmars-d-learn mailing list