Dynamic array and foreach loop

Alex Parrill via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 9 08:48:03 PDT 2015


On Sunday, 9 August 2015 at 15:37:23 UTC, Binarydepth wrote:
>
> So I should use the REF like this ?
>
> import std.stdio : writeln;
> void main()     {
>         immutable a=5;
>         int[a] Arr;
>         foreach(num; 0..a)      {
>                 Arr[num] = num;
>         }
>         foreach(num, ref ele; Arr)      {
>                 writeln(Arr[ele]+1);//Using the REF
>         }
> }

No. `ele` is the array element; reindexing the array with it is 
incorrect. `ref` just means that you can assign back to the array 
(like `ele = 123; assert(Arr[num] == 123);`); it's unnecessary 
here though.



More information about the Digitalmars-d-learn mailing list