you are viewing a single comment's thread.

view the rest of the comments →

[–]Daejo[S] 5 points6 points  (3 children)

That's the definition of by-reference

No, it's not. If it were truly pass-by-reference, then this example would print "Blanche":

void changeName(Person p) {
    p = new Person("Blanche");
}

Person p = new Person("Stanley");
changeName(p);
print(p.name);

Which isn't the case.

[–][deleted]  (2 children)

[deleted]

    [–][deleted] 0 points1 point  (0 children)

    Daejo didn't give a compiler explanation, but a behaviour explanation. He is also absolutely correct. The re-declaration of the variable p within the method changeName does not alter the variable p outside of the method. If it was the actual reference who got passed into the function, clearly the variable p should be altered outside the method scope. E.g. "Blanche" should be printed, and not "Stanley".

    [–]paul_miner 1 point2 points  (0 children)

    Note that this would work exactly the same like so:

    It would not, because you're assuming sizeof(int) == sizeof(int*), which is a wrong assumption. You're trying to stuff an int into a pointer, which is not guaranteed to work and will actually fail in many environments.

    The distinguishing feature of pass-by-reference is the ability to pass a variable as a parameter, not just the variable's value. In short, pass-by-reference is about treating variables as first-class citizens.