No index for cycle ranges

Steven Schveighoffer schveiguy at yahoo.com
Thu Jun 2 14:46:58 PDT 2011


On Thu, 02 Jun 2011 17:38:38 -0400, Andrej Mitrovic  
<andrej.mitrovich at gmail.com> wrote:

> Well actually all I wanted was a counter variable. I can put the thing
> in a for loop or while loop, but I thought that a counter variable is
> something that the compiler can always add without too much thinking.
>
> I guess things aren't so simple.

In fact, if indexes for ranges were implemented during foreach, it would  
*have* to be this way.  An explanation:

Note that foreach(x; range) translates to:

auto _r = range;
for(; !_r.empty; _r.popNext())
{
    auto x = _r.front;
    ...
}

So think about this for a second, if you wanted to add an index variable,  
what is the index of _r.front()?  In the case of simple arrays, it's  
*always* 0!  So the index would have to be tracked by the loop, not by the  
range.

But we'd also need a way to override this.  For instance, a range on an  
associative array, the index is not a sequential integer series starting  
at 0.

So I'm not sure how this would be solved, but it's definitely complicated.

Note that opApply solves this beautifully, since opApply has it's own  
temporary scope where you can track anything you want.

-Steve


More information about the Digitalmars-d-learn mailing list