Are Arguments Passed by Value or Reference?

12,275 views
Skip to first unread message

pongad

unread,
Oct 10, 2011, 10:32:08 AM10/10/11
to General Dart Discussion
Hi all,
I tried running this code on dart board earlier:

main() {
var y = 1;
print(y);
incr(y);
print(y);
}

incr(x) {
x = x+1;
}

The output is 1 and 1. So y was passed to incr by value?

However, in this code:

class myClass {
var x;
myClass(this.x);
}

incr(myClass c) {
c.x = c.x+1;
}

main() {
var obj = new myClass(1);
print(obj.x);
incr(obj);
print(obj.x);
}

This output is 1 and 2. So obj (in main) was passed to incr by
reference? What are the rules of passing arguments in Dart? I came
from languages with explicit pointers so this is a little confusing to
me.

Emily Fortuna

unread,
Oct 10, 2011, 1:57:03 PM10/10/11
to pongad, General Dart Discussion
Primitives (like int, bool, and num) are passed by value. Objects are
passed by reference. This is the same behavior as in Java for passing
arguments.

Sverre Rabbelier

unread,
Oct 10, 2011, 3:04:24 PM10/10/11
to Emily Fortuna, pongad, General Dart Discussion
Heya,

On Mon, Oct 10, 2011 at 19:57, Emily Fortuna <efor...@google.com> wrote:
> Primitives (like int, bool, and num) are passed by value. Objects are
> passed by reference. This is the same behavior as in Java for passing
> arguments.

In a neighboring thread someone said everything is an object, no
primitives. Can you explain?

--
Cheers,

Sverre Rabbelier

Daniel Rice (דניאל רייס)

unread,
Oct 10, 2011, 3:10:53 PM10/10/11
to Sverre Rabbelier, mi...@dartlang.org
  The formal parameter 'x' in the function 'incr' is essentially a new variable containing a reference to whatever is passed in.  The line 'c.x = c.x + 1' assigns a new value to 'c.x', which is the same instance variable as 'obj.x' in the caller.  However, the line 'x = x + 1' assigns 'x + 1' to the formal parameter x, which has no effect on the reference 'y' in main().

Dan
--
Daniel Rice | Software Engineer | ri...@google.com | 415-613-2441

Ramón

unread,
Oct 10, 2011, 3:11:43 PM10/10/11
to General Dart Discussion
Emily, a little more clarification please. If it's like Java is it
actually a copy of the reference?

Ramón

unread,
Oct 10, 2011, 3:15:13 PM10/10/11
to General Dart Discussion
Nevermind, Dan's explanation cleared it up. Thanks.
Reply all
Reply to author
Forward
0 new messages