Search code examples
javac++cpass-by-referencecall-by-value

Why do programmers say that "pass by reference" is really "passing references by value?" Why is that important?


I know the whole concept of passing by reference in C & C++, and the similar concept of only pass by value in Java. But in a point of view Everything is pass by value isnt it? In C we pass a pointer of the variable to the function. So we are just passing the value of the reference of to the function. And that is the reason we say Java doesnt support pass by reference because we just pass the value of reference variable to the functions. So we pass the reference by value. Though in C++ there is a way of passing by reference since we can pass arguments and the function will work with the same memory location using this format

void swap(int &x, int &y)

But passing by reference by pointers in C is just passing the pointers by value.

void swap(int* x, int* y)

I know the question might seem a bit stupid, but i feel there is a big gaping hole in the whole concept that i have. So what is the actual defination of call by reference, is this just a pseduo name of call by value in another context?


Solution

  • Two main points:

    • There is no call by reference in C.
    • Pass by value and pass by reference are different. They are not same.

    Pass by value: the called function creates a new set of variables in stack and copies the values of the arguments into them.

    Pass by reference: instead of passing values to the function being called, references/pointers to the original variables are passed.

    Why do programmers say that “pass by reference” is really “passing references by value?”

    In passing references/pointers to the original variables, in fact objects/addresses are passed by value. So, you can say pass by reference is passing reference by value but this doesn't imply that pass by reference is pseudo name of pass by value. The difference between the two is well explained in this answer. I am copying the excerpt:

    If I tell you the URL, I'm passing by reference. You can use that URL to see the same web page I can see. If that page is changed, we both see the changes. If you delete the URL, all you're doing is destroying your reference to that page - you're not deleting the actual page itself.

    If I print out the page and give you the printout, I'm passing by value. Your page is a disconnected copy of the original. You won't see any subsequent changes, and any changes that you make (e.g. scribbling on your printout) will not show up on the original page. If you destroy the printout, you have actually destroyed your copy of the object - but the original web page remains intact.