Foreach problem

Bill Baxter wbaxter at gmail.com
Sat Jan 10 19:08:11 PST 2009


On Sun, Jan 11, 2009 at 11:33 AM, Tim M <a at b.com> wrote:
>
> Why is this an error. Dmd wants to make sure that I declare a new variable
> in the foreach statement and not use an existing one?
>
> module test;
>
> void main()
> {
>        int i;
>        int[] nums;
>        foreach(i; nums)
>        {
>                //
>        }
> }
>
>
> dmd test.d
>
> test.d(7): Error: shadowing declaration test.main.i is deprecated

I think this should be allowable.
It's basically an unfortunate side effect of the decision to make the
loop variables in foreach implicitly 'auto'.
I'd kinda forgotten about that, but I remember when I first saw it
thinking it looked like a particularly odious bit of special casing
just in the name of saving a few keystrokes.  It's the only place in D
where you can declare a variable without any type or storage class
AFAIK.    The only think like it is some of the crazy 'is( )'
expressions where you can define a new type without any 'alias' or
'typedef'.

I wouldn't cry if D2 made specifying 'auto' a requirement in foreach.
And allowed using an outer variable as the index like every other
loop.  It would certainly be more consistent.

--bb


More information about the Digitalmars-d-learn mailing list