Changing elements during foreach

qznc qznc at web.de
Mon Oct 21 03:55:49 PDT 2013


On Monday, 21 October 2013 at 10:31:51 UTC, Krzysztof Ciebiera 
wrote:
> 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.

The behavior of D's slices is often unintuitive. To understand 
them, read this article: http://dlang.org/d-array-article.html


More information about the Digitalmars-d-learn mailing list