Arrays passed by almost reference?
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.org
Thu Nov 5 14:10:03 PST 2009
Ali Cehreli wrote:
> Thanks for all the responses.
>
> And yes, I know that 'ref' is what works for me here. I am trying to figure out whether I should develop a guideline like "always pass arrays with 'ref', or you may face surprises."
>
> I understand it very well now and was able to figure out a way to cause some bugs. :)
>
> What can be said about the output of the following program? Will main.a[0] be printed as 1 or 111?
>
> import std.cstream;
>
> void modify(int[] a)
> {
> a[0] = 1;
>
> // ... more operations ...
>
> a[0] = 111;
> }
>
> void main()
> {
> int[] a;
> a ~= 0;
> modify(a);
>
> dout.writefln(a[0]);
> }
>
> It depends on the operations in between the two assignments to a[0] in 'modify':
>
> - if we leave the comment in place, main.a[0] is 111
>
> - if we replace the comment with this code
>
> foreach (i; 0 .. 10) {
> a ~= 2;
> }
>
> then main.a[0] is 1. In a sense, modify.a caused only "some" side effects in main.a. If we shorten the foreach, then main.a[0] is again 111. To me, this is at an unmanagable level. Unless we always pass with 'ref'.
>
> I don't think that this is easy to explain to a learner; and I think that is a good indicator that there is a problem with these semantics.
The ball is in your court to define better semantics.
Andrei
More information about the Digitalmars-d
mailing list