[Issue 16149] foreach_reverse can't handle index variable of type int

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Mon Jun 13 05:24:25 PDT 2016


https://issues.dlang.org/show_bug.cgi?id=16149

--- Comment #7 from Steven Schveighoffer <schveiguy at yahoo.com> ---
(In reply to Ketmar Dark from comment #6)
> (In reply to Steven Schveighoffer from comment #5)
> > int x = a.length would continue to be invalid (on 64-bit CPU). It's just for
> > foreach_reverse.
> 
> then i'll inevitably ask why `int x = a.length;` is invalid, but
> `foreach_reverse (int x, v; a)` is valid. that `foreach` obviously does the
> assign under the hood (at least this is the most practical way to imagine
> it).

foreach_reverse could be implemented like this:

for(size_t __idx = a.length; __idx; --__idx)
{
   int x = cast(int)(__idx - 1);
   auto v = a[__idx-1];
   ... // your code
}

In fact, if foreach was implemented similarly (always using hidden size_t to
iterate and assigning to your chosen variable as the index), it wouldn't get
into an infinite loop.

> the only way to skip that "hidden assign" is to redefive `foreach_reverse`
> completely — by still using increasing index in it, so x will go from 0 upto
> limit. otherwise you just introducing a random pseudo-solution by randomly
> breaking the rules.

The definition of foreach_reverse on an array is that it works exactly like
foreach, but visits the elements in reverse. There is no definition of how it
does this, so my implementation is valid. (in fact, the spec says the index
must be int, uint, or size_t, but I think this is a relic from 32-bit, non VRP
days).

The fact that the implementation rejects it is an implementation detail
leaking. It's not a *bad* thing, but clearly this is the case of the compiler
being too cautious, because it's OK with you being stupid in foreach.

--


More information about the Digitalmars-d-bugs mailing list