Static arrays passed by value..?

Lionello Lunesu lio at lunesu.remove.com
Sat Aug 7 09:39:48 PDT 2010


On 2010-08-07 9:26, simendsjo wrote:
> The spec for array says:
> Static arrays are value types. Unlike in C and D version 1, static
> arrays are passed to functions by value. Static arrays can also be
> returned by functions.
>
> I don't get the "static arrays are passed to functions by value" part.
>
> Here I am passing in a static and dynamic array. Both are passed by
> value, and the function can modify the array of both
>
> {
> void func(int[] arr, void* ptr) {
> arr[0] = 9;
> assert(&arr != ptr);
> }
>
> int[3] a = [1,2,3];
> func(a, &a);
> assert(a == [9,2,3]); // changed..
>
> int[] b = [1,2,3];
> func(b, &b);
> assert(b == [9,2,3]);
> }

When you use "int[]" as the parameter type, the array is passed by 
reference as a slice of the original array. If you write the function 
like this:

fund(int[3] arr, void* ptr) {...}

Now the array is passed by value and a copy is made.


More information about the Digitalmars-d-learn mailing list