Error: shadowing declaration is deprecated

Jarrett Billingsley kb3ctd2 at
Sun Dec 24 16:17:03 PST 2006

"Bill Baxter" <dnewsgroup at> wrote in message 
news:emn3rk$828$1 at
> Ah ok, good point.  This is because foreach(u; blah) is always taken to 
> mean foreach(auto u; blah).   It's a little special case to save some 
> typing.  I think it's a bad idea to have such a special case, but oh well. 
> Now that you mention it I do remember ranting about this one at one point, 
> but I wasn't annoyed enough by it to follow through.  For one it means 
> that you can't have a loop variable in a foreach that 'escapes', which 
> eliminates some handy patterns like
>    char[] u;
>    foreach(u; FPUsers) { if match(u) break; }
>    /* use u here */
> Maybe there's some reason for this that has to do with how foreach is 
> implemented for classes?  But I don't see how that could be the case when 
> this certainly works:
>    char[] u;
>    foreach(utmp; FPUsers) { u=utmp; if match(u) break; }
>    /* use u here */

Foreach is implemented the same way for all types, not just classes -- the 
body is always converted to a delegate which is used as a callback in some 
kind of apply function.  The indices are nothing but the parameter list for 
that delegate (which is why 'inout' is possible), hence this restriction. 
Your example works fine because nested functions can access outer function 
variables.  In this case, u is an outer variable to the loop body.

If you're wondering why foreach loops are implemented this way, it's because 
it's a very clever solution to some iteration problems.  It makes it much 
easier to iterate through non-linear structures (like AAs), and it also 
doesn't require any allocation of an "iterator" object.  All the iteration 
is performed by the apply function, which makes the most sense.

> Anyway foreach could certainly be smarter than it is.  For instance I 
> believe the magic 'int' return value that opApply implementations must 
> handle and diligently return back to their caller could be eliminated with 
> some hidden variables on the stack.  But Walter and others here don't seem 
> to see that as a wart for some reason.

That would be nice.  It would just be a hidden variable in the enclosing 
function, and the foreach body would just set that result to the appropriate 
value before returning.  It would still have to return something, though, to 
let the apply function know when to stop iterating.  A bool would work fine. 

More information about the Digitalmars-d-learn mailing list