About foreach loops

Steven Schveighoffer schveiguy at yahoo.com
Wed Jun 15 08:02:41 PDT 2011


On Wed, 15 Jun 2011 10:35:33 -0400, Caligo <iteronvexor at gmail.com> 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.");
>   }

That code relies on undocumented behavior.  It's likely to fail on some  
other D compiler.

We can't worry about existing code that uses undocumented "features" of  
dmd.  It's utilizing the knowledge of how D rewrites the foreach  
statement, not how foreach is documented to work.

Besides, I think this case is very uncommon.  A better implementation for  
such a thing would be:

foreach(i;  0..5)
    writeln(i * 2, " is even.");

-Steve


More information about the Digitalmars-d mailing list