Foreach problem

Denis Koroskin 2korden at gmail.com
Sat Jan 10 23:31:51 PST 2009


On Sun, 11 Jan 2009 10:08:47 +0300, Tim M <a at b.com> wrote:

> On Sun, 11 Jan 2009 19:56:55 +1300, Denis Koroskin <2korden at gmail.com>  
> wrote:
>
>> On Sun, 11 Jan 2009 06:04:01 +0300, Tim M <a at b.com> wrote:
>>
>>> On Sun, 11 Jan 2009 15:59:26 +1300, Tim M <a at b.com> wrote:
>>>
>>>> On Sun, 11 Jan 2009 15:50:54 +1300, Daniel Keep  
>>>> <daniel.keep.lists at gmail.com> wrote:
>>>>
>>>>>
>>>>>
>>>>> Tim M 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
>>>>>
>>>>> Yes; as the error states, you're not allowed to define variables  
>>>>> with the same name as variables in an enclosing scope any more.
>>>>>
>>>>>    -- Daniel
>>>>
>>>> Why does it still work for some objects?
>>>
>>>
>>> This works:
>>>
>>>
>>> module test;
>>>
>>> class A
>>> {
>>> 	this()
>>> 	{
>>> 		//
>>> 	}
>>> }
>>>
>>> class B
>>> {
>>> 	this()
>>> 	{
>>> 		//
>>> 	}
>>>   	int opApply (int delegate (inout B) dg)
>>>          {
>>>                  return 1;
>>>          }
>>> }
>>>
>>> void main()
>>> {
>>> 	A a;
>>> 	B b;
>>> 	foreach(a; b)
>>> 	{
>>> 		//
>>> 	}
>>> }
>>>
>>
>> It is a bug and should be reported.
>>
>
>
> Yep that probibly is a slight bug. What I would like to know is why cant  
> I do foreach with primitive types like I can with objects.

You can use foreach to iterate over arrays and tuples, if that's what you mean. Iterating over over primitive types makes little sense.

> The objects  
> use an existing variable but an int would require a new int defined with  
> the foreach params.

You got it wrong, foreach never use an existing variable. Try yourself:

void main()
{
    B b;
    foreach (a; b)
    {
    }
}

Variable shadowing is disallowed for this very reason - to avoid "what variable do I use here" type of confusion.

The code you provided is incorrect, but compiler currently accepts it (which is a bug). You should remove "A a;" from the main, it is never used anyway.


More information about the Digitalmars-d-learn mailing list