foreach bug, or shoddy docs, or something, or both.

Dave Jones dave at jones.com
Sun Dec 10 02:02:31 UTC 2017


Foreach ignores modification to the loop variable...

import std.stdio;

void main() {
     int[10] foo = 10;

     foreach (i; 0..10) // writes '10' ten times
     {
         writeln(foo[i]);
         if (i == 3) i+=2;
     }
}

 From the docs...

"ForeachType declares a variable with either an explicit type, or 
a type inferred from LwrExpression and UprExpression. <**snip**> 
If Foreach is foreach, then the variable is set to LwrExpression, 
then incremented at the end of each iteration."

That's clearly not what is happening, yes we get a variable, but 
either its a copy of the actual loop variable, or something else 
is going on. Because if we got the actual variable then 
modifications to it would not be lost at the end of the current 
iteration.

My opinion is the it should pick up the modification. I think 
people expect the foreach form to be a shorthand for a regular 
for loop.

Failing that it should be an error to write to the loop variable.

An at the least it should be explained in the documentation that 
actually you get a copy of the loop variable so modifying it is a 
waste of time.


More information about the Digitalmars-d mailing list