Changing elements during foreach

Krzysztof Ciebiera ciebie at mimuw.edu.pl
Mon Oct 21 03:55:16 PDT 2013


On Monday, 21 October 2013 at 10:41:38 UTC, Alexandr Druzhinin 
wrote:
> 21.10.2013 17:31, Krzysztof Ciebiera пишет:
>> void main()
>> {
>>     int a[][] = [[1,2,3]];
>>     foreach(x; a)
>>     {
>>         x[0] = 0;
>>         x ~= 4;
>>     }
>>     writeln(a);
>> }
>> ...
>> &) 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, when exactly my local copy of data should be created? Now it 
is created during appending element to an array (when I switch 
instructions order, first append x ~= 4, then set x[0] to 0, as a 
result I get [1,2,3]). Maybe I should get a warning (like when 
hiding variable from outer scope)?


More information about the Digitalmars-d-learn mailing list