Why are fixed length arrays passed by value while variable are passed by reference?

Simen Kjaeraas simen.kjaras at gmail.com
Thu Apr 18 08:23:02 PDT 2013


On 2013-04-18, 16:20, ixid wrote:

>> An array is represent using a struct with a pointer to the array data  
>> and the length, like this:
>>
>> struct Array
>> {
>>     void* ptr;
>>     size_t length;
>> }
>>
>> The struct is passed by value, but since it contains a pointer to the  
>> data it will be passed by reference. Note that if you do:
>>
>> void foo (int[] a)
>> {
>>     a ~= 3;
>> }
>>
>> auto b = [3, 4];
>> foo(b);
>>
>> The caller will not see the change made by "foo".
>>
>> Don't know if this explanation helped you to understand.
>
> What does a fixed length array look like when passed, doesn't it have a  
> similar payload of data and length? I take it you mean the struct method  
> is the variable length array.


The fixed length array is much more similar to a struct. An int[2], for
instance, is in many ways equivalent to struct { int a; int b; }.
Two ways this is visible is that static arrays are allocated on the stack,
and take up space in a struct or class the same way a struct would:

struct S1 {
     int[] a;
}
static assert( S1.sizeof == int[].sizeof );

struct S2 {
     int[17] a;
}
static assert( S2.sizeof == 17 * int.sizeof );


Also, like Jacob wrote, there is the difference of ref/value semantics
when embedded in a struct/class. If I have these two functions:

void foo1( S1 s ) {
    s.a[0] = 7;
}

void foo2( S2 s ) {
    s.a[0] = 7;
}

void test( ) {
    S1 s1 = S1(new int[4]);
    S2 s2 = S2();
    foo1(s1);
    foo2(s2);
}

The values in s1 will have changed, while those in s2 will not.

All in all, static arrays are treated as value types everywhere else,
and so treating them as value types when passed to a function makes
more sense.

-- 
Simen


More information about the Digitalmars-d-learn mailing list