About foreach loops

Steven Schveighoffer schveiguy at yahoo.com
Wed Jun 15 08:40:47 PDT 2011


On Wed, 15 Jun 2011 11:23:55 -0400, Caligo <iteronvexor at gmail.com> wrote:

> On Wed, Jun 15, 2011 at 9:44 AM, KennyTM~ <kennytm at gmail.com> wrote:
>> On Jun 15, 11 22:35, Caligo wrote:
>>>
>>> You can create a temporary if you like:
>>>
>>>   foreach(i; 0..10){
>>>     int ii = i + 1;
>>>     writeln(ii, " ");
>>>   }
>>>
>>> Which outputs:
>>> 1 2 3 4 5 6 7 8 9 10
>>>
>>>
>>> The problem with trying to "fix" foreach is that it would create
>>> problems of its own.  The following code would not behave correctly:
>>>
>>>   foreach(i; 0..10){
>>>     if(i&  1)
>>>       i += 1;
>>>     writeln(i, " is even.");
>>>   }
>>>
>>> not to mention all the code that's already using foreach.
>>
>> If the code rely on the 'implicit ref' behavior of 'i', the code is  
>> doing it
>> wrong. The spec never mentioned what happened when the variable is  
>> modified
>> in a ForeachRangeStatement. I believe it is more sane if modifying 'i'  
>> is
>> disallowed unless 'ref' is used.
>>
>
>
> This should be a compile time error:
>
>   foreach(i; 0..10){
>     i += 1;
>     write(i, " ");
>   }

No, it should be legal and write 1 2 3 4 5 6 7 8 9 10

>
> This should be legal.
>   foreach(ref i; 0..10){
>     i += 1;
>     write(i, " ");
>   }

If this is legal, it should write 1 3 5 7 9

I have no problem with it being legal.

-Steve


More information about the Digitalmars-d mailing list