suggested change to foreach index

Sean Kelly sean at f4.ca
Thu Jun 8 09:06:37 PDT 2006


Deewiant wrote:
> Sean Kelly wrote:
>> What's weird to me is if I do this:
>>
>>     void main()
>>     {
>>         int    i;
>>         char[] arr = "abc def";
>>
>>         foreach( i, c; arr )
>>         {
>>             printf( "%i\n", i );
>>             if(' ' == c)
>>                 break;
>>         }
>>         printf( "\n%i\n", i );
>>     }
>>
>> Then the output is:
>>
>>     0
>>     1
>>     2
>>     3
>>
>>     0
>>
>> So the code compiles without a type for i in the foreach, but rather
>> than use the instance of i in the surrounding scope a local value is
>> used instead.  The spec isn't clear on what should happen here, but I
>> would have guessed that the final value displayed would be 3, not 0.
>>
>>
>> Sean
> 
> 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.


Sean



More information about the Digitalmars-d mailing list