Passing by Reference vs. Passing by Value: A Comparison Between C/C++ and Java and JavaScript
If you learned programming through JavaScript, or even Java, you are probably unfamiliar with the concept of pointers.
Consider the following simple program:
The output for the code above is:
First: 1
Second: 3
If you’re wondering why, then please read on!
Pointers
The key difference lies in the arguments passed through the functions addTwo
and add_two
. Note that the type for the argument is not int
but int*
. This a concept found in C/C++ and other ‘C-like’ languages known as a Pointer. Even if pointers are unfamiliar for you, the underlying concept is something you might recognize. Essentially, a pointer is a variable that holds the address in memory where this value type is defined. An asterisk *
after a type indicates that it is a pointer of that type rather than the type itself. For example, int *
is a declaration not for an integer value, but an address in memory of an integer value. So if we look at our add_two
function, we see that it expects to receive an address rather than an integer value.
So how do we obtain the value at that address the pointer is pointing to? To do so in C/C++, we use what is known as a dereference operator (which is coincidentally also a *
). By placing the asterisk before a pointer variable, we tell C/C++ to give us the value stored in that memory address. So from the example above, *arg
refers to the value that we passed in, which is 1
.
“Okay, but what about that ‘&’ operator?”
The ampersand &
is probably more familiar to you in terms of its use as a logical AND operator in the form of &&
. While that is still the case in C/C++, the single &
represents the opposite of the asterisk *
, in that it is known as the reference operator. Just like we have the *
to get a value at an address in memory, we use the &
to get the address in memory of a value. Because add_two
expected an integer pointer and we declared second
as just an integer value, we need to pass &second
which is the address, or the pointer to the value of second
.
Passing By Value vs Passing By Reference
Thus,addTwo
is a function which passes the argument by value, while add_two
is passing the argument by reference. We see the difference between to two illustrated by the fact that the output shows our variable first
does not change, even though we ostensibly incremented it by two with the line arg = arg + 2
, and our variable second
has changed.
In Java and Javascript, we know of that primitive types are passed by value, and objects like arrays are passed by reference. We can see this happening in the following two examples:
In C (not C++), everything is passed by value only. Which means pointers are absolutely necessary to accomplish array manipulation like the above JS and Java examples. In C++, having pointers allows flexibility, though classic pointers have recently fallen out of popularity in favor of Smart Pointers (we can go over that another day!).