Foreach problem
Steven Schveighoffer
schveiguy at yahoo.com
Mon Jan 12 13:25:48 PST 2009
"Denis Koroskin" 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.
I'm not so sure.
Would you say this is a bug (it compiles)?
int foo()
{
int i;
int innerfoo(int i)
{
return i;
}
return innerfoo(2); // returns 2
}
because that's basically what a foreach does when using opApply: create an
inner function and then pass a delegate pointing to that function to
opApply.
I think the difference between the two is that the compiler handles foreach
on an array in a special manner without using an inner function/delegate.
This also fails to compile:
void main()
{
A a;
A[] b;
foreach(a; b)
{
//
}
}
More information about the Digitalmars-d-learn
mailing list