Arrays passed by almost reference?

Nick Sabalausky a at a.a
Thu Nov 5 13:34:21 PST 2009


"Frank Benoit" <keinfarbton at googlemail.com> wrote in message 
news:hcvff9$9cr$1 at digitalmars.com...
> Ali Cehreli schrieb:
>> I haven't started reading Andrei's chapter on arrays yet. I hope I won't 
>> find out that the following behavior is expected. :)
>>
>> import std.cstream;
>>
>> void modify(int[] a)
>> {
>>     a[0] = 1;
>>     a ~= 2;
>>
>>     dout.writefln("During: ", a);
>> }
>>
>> void main()
>> {
>>     int[] a = [ 0 ];
>>
>>     dout.writefln("Before: ", a);
>>     modify(a);
>>     dout.writefln("After : ", a);
>> }
>>
>> The output with dmd 2.035 is
>>
>> Before: [0]
>> During: [1,2]
>> After : [1]
>>
>> I don't understand arrays. :D
>>
>> Ali
>>
>
> int[] a;
> a is kind of a pointer, one with the extra length information.
> When passed to modify(), a is passed by-value, the contained data is
> certainly passed by-reference since a points to the data.
>
> This is why the a.length was not updated.
>
> If you change "modify" to :
> void modify(ref int[] a){...
>
> it should work as you expected.

Or you could force totally-by-value semantics with:

void modify(const(int)[] a){
int[] _a = a.dup;
...

(Anyone know if scope can be used on that to allocate it on the stack, or is 
that just for classes?)

I do agree it can sometimes be a bit weird though. But like others 
mentioned, it's kind of a necissary evil, and once you understand how the 
arrays work under-the-hood, it becomes a bit easier.





More information about the Digitalmars-d mailing list