foreach

Manu via Digitalmars-d digitalmars-d at puremagic.com
Thu Jun 12 19:26:34 PDT 2014


On 13 June 2014 04:04, Nick Sabalausky via Digitalmars-d
<digitalmars-d at puremagic.com> wrote:
> On 6/12/2014 11:00 AM, Manu via Digitalmars-d wrote:
>>
>> I often find myself wanting to write this:
>>    foreach(; 0..n) {}
>> In the case that I just want to do something n times and I don't
>> actually care about the loop counter, but this doesn't compile.
>>
>> You can do this:
>>    for(;;) {}
>>
>> If 'for' lets you omit any of the loop terms, surely it makes sense
>> that foreach would allow you to omit the first term as well?
>> I see no need to declare a superfluous loop counter when it is unused.
>>
>
> I can't imagine this has ever been a significant issue for anyone. But that
> said, I certainly can't disagree with it, and wouldn't object to it.
>

It gets awkward when you nest, using '_' leads to '__', and
personally, I would expect an 'unreferenced variable' warning for the
unused loop counter. I like warnings hassling me about unused
variables.
I also object to the inconsistency with for(;;). Recall Scott Myers talk...

It's theoretically an optimisation too; capturing front may be a
costly operation that's not required. Ranges maintain their counters
internally, there's no reason to emit code to capture a local copy of
'front' if it's not used. popFront and empty don't imply a byVal copy,
they usually just update range counters.

I agree, it's trivial, just throwing it out there for opinion.


More information about the Digitalmars-d mailing list