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

Ali Çehreli acehreli at yahoo.com
Thu Apr 18 08:35:02 PDT 2013


On 04/18/2013 07:20 AM, ixid wrote:

Jacob Carlborg said:

 >> 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 terms "array" and "slice" are commonly interchanged but I think it 
adds to the confusion. The above is the definition of a slice. An array 
is simply a collection of objects placed next to each other.

 >> 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?

No. It is all of the elements side by side. That is the definition of an 
array.

     int[3] a;
     assert(a.sizeof == ((a[0]).sizeof * a.length));
     assert(cast(void*)&a == cast(void*)&(a[0]));

A fixed-length array does not have a ptr or length member. The former is 
simly the address of the fixed-length array itself and the latter is a 
compile-time constant.

 > I take it you mean the struct method
 > is the variable length array.

Yes. The struct above is a slice. (Although, in reality length is 
defined before ptr.)

Ali



More information about the Digitalmars-d-learn mailing list