suggested change to foreach index

Deewiant deewiant.doesnotlike.spam at gmail.com
Thu Jun 8 09:14:48 PDT 2006


Sean Kelly wrote:
> Deewiant wrote:
>> Sean Kelly wrote:
>>>     void main()
>>>     {
>>>         int    i;
>>>         char[] arr = "abc def";
>>>
>>>         foreach( i, c; arr )
>>>         {
>>>             printf( "%i\n", i );
>>>             if(' ' == c)
>>>                 break;
>>>         }
>>>         printf( "\n%i\n", i );
>>>     }
>>
>> It creates a new scope, just like for loops:
>>
>> int i = 5;
>> for (int i = 0; i < 3; ++i)
>>     writefln(i); // 0 to 2
>> writefln(i); // 5
> 
> Yes, but my example was equivalent to this (I thought):
> 
>     int i = 5;
>     for (i = 0; i < 3; ++i)
>         writefln(i); // 0 to 2
>     writefln(i); // 2
> 
> ie, the lack of a type makes the "i=0" an assignment, not a declaration
> with an initializer.  The i from the surrounding scope is used.  I
> expected foreach to behave the same way, but apparently it doesn't.
> 

I guess it's the type inference that makes it so confusing to some. Earlier,
after all, we had to write:

foreach (int i, char[] c; arr)

Instead of the modern terse version:

foreach (i, c; arr)

In the longer version, it's presumably more clear that the i is a new "int i".



More information about the Digitalmars-d mailing list