foreach

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Thu Jun 12 21:08:10 PDT 2014


On Thu, 12 Jun 2014 23:55:20 -0400, Manu via Digitalmars-d  
<digitalmars-d at puremagic.com> wrote:

> On 13 June 2014 13:42, Steven Schveighoffer via Digitalmars-d
> <digitalmars-d at puremagic.com> wrote:
>> On Thu, 12 Jun 2014 23:34:27 -0400, Manu via Digitalmars-d
>> <digitalmars-d at puremagic.com> wrote:
>>
>>> On 13 June 2014 13:04, Daniel Murphy via Digitalmars-d
>>> <digitalmars-d at puremagic.com> wrote:
>>>>
>>>>
>>>> i,j,k,etc work just fine.  Are you really nesting your loops that  
>>>> deeply?
>>>
>>>
>>> Giving explicit names pollutes the local namespace, and the point
>>> below about unreferenced variable warnings if you give explicit names.
>>
>>
>> i, j, k are traditionally loop variables. People have been using them  
>> for
>> decades without conflicting their other variables.
>>
>>>>
>>>> The compiler's optimizer will do that just fine.
>>>
>>>
>>> Not necessarily. The range might be a lib, and non-pure. The compiler
>>> can't optimise/inline/eliminate the call if it doesn't have code.
>>> In my experience this is common, I frequently wrap C api's in D-style
>>> ranges. Potentially a lot of unnecessary calls to
>>> C_API_GetItem(itemIndex).
>>
>>
>> 2 options:
>>
>> foreach(i; 0..r.walkLength)
>> {
>> }
>
> walkLength might not be known ahead of time. Lists?

walkLength is for ranges you don't know the length ahead of time. It  
executes the popFront/empty routines until exhaustion, returning the  
number of times popFront was required.

And it should be trivial to create a wrapper that does not access front,  
but instead generates an index.

>
>
>> or
>>
>> while(!r.empty)
>> {
>>    r.popFront();
>> }
>
> This modifies 'r', which foreach doesn't do. I'm forced to capture a
> copy for the sake of the loop? Sounds like a likely place for bugs to
> emerge... convert foreach code to this code as an optimisation, and a
> consecutive loop now terminates immediately changing program
> behaviour...

Then use the first option.

-Steve


More information about the Digitalmars-d mailing list