Remember that pointer is a reference, but the vice-versa may not be true. Though pass by reference and pass by pointers serve the same purpose, there are subtle differences between both. Hope the examples and comparisons have given you enough clarity on pass by reference and how it is different from pass by value and pass by pointer. Using &, we can get the address of reference (because the address is the same as that of the original variable) Uses ‘&’ to reference the address of variable. Value can be implicitly referenced using the reference name.Ĭan be reassigned to another memory locationĬan’t be reassigned to another memory address The dereferencing operator * gives the value of the variable Now, let us compare the two operations side-by-side – PASSING VARIABLES BY POINTERĬreates a pointer that stores memory address of a variableĬreates another name for the same variable (alias) Pass by Pointer vs Pass by Reference: Head to Head Comparison
PASS BY REFERENCE C++ CODE
The code is modified version of the original code from here. For example – void doubleTheValue (int a) In effect, whatever changes are made to the variables inside the called function are not reflected to the actual variables with which the function is called (because they are two different copies whose memory addresses are different). When you call a function with pass by value, two copies of variables with the same value are created.
If you would like to learn more about C++, do it here. The examples I have written are in C++ because C++ uses all the three and it will be easier for us to compare and understand each of them. To discuss pass by reference in detail, I would like to explain to you the other two ways as well, so that the concepts are planted in your mind forever. The most common language that uses pass by reference in C++. There are three ways to pass variables to a function – pass by value, pass by pointer and pass by reference. Pass by Pointer vs Pass by Reference: Head to Head Comparison.How Java and other languages ‘pass by reference’.