arrays and foreach

Ali Çehreli acehreli at yahoo.com
Mon Apr 16 17:01:14 PDT 2012


On 04/16/2012 04:56 PM, darkstalker wrote:
> i have this example program:
>
> ---
> void main()
> {
> int[3] a;
> foreach (p; a)
> p = 42;
> writeln(a);
> }
> ---
>
> after running it, i expect to get [42, 42, 42] but instead i get [0, 0,
> 0] (i know that you can do a[] = 42, it's just a trivial example). So it
> seems that you cannot write into the array because the elements are
> being passed by value each iteration. It possible to have 'p' passed by
> reference?

Yes:

     foreach (ref p; a)

Ali




More information about the Digitalmars-d-learn mailing list