Changing elements during foreach

Alexandr Druzhinin drug2004 at bk.ru
Mon Oct 21 03:41:34 PDT 2013


21.10.2013 17:31, Krzysztof Ciebiera пишет:
> Is the following compiler behavior consistent with language specification?
>
> import std.stdio;
>
> void main()
> {
>      int a[][] = [[1,2,3]];
>      foreach(x; a)
>      {
>          x[0] = 0;
>          x ~= 4;
>      }
>      writeln(a);
> }
>
> I understand why thw program could output [1,2,3] (like in C++ without
> &) or [0,2,3,4] (python, C++ ref). But [0,2,3]? It was unpleasant surprise.
It's expected.
foreach(ref x; a) == C++ with &
but without ref you get the first element of a - i.e. [1, 2, 3] then set 
x[0] = 0 so you get [0, 2, 3]. But when you append 4 you append it to 
local copy of x - because there is no 'ref'. So your local copy of x 
became [0, 2, 3, 4] but when scope is gone you get unmodified copy of a 
with old array [0, 2, 3]. Changing the first element without ref 
possible because you modify inner array which is reference itself.


More information about the Digitalmars-d-learn mailing list