C++ call by reference vs call by value

sinclair
2 min readNov 5, 2020

In c++ there are two types of calling in the functions. It seems confusing but there is a distinguishable difference between them.

What’s the difference?

Call by value executes with the argument which is ‘value’ type. Call by reference refers the address of the argument. In other words, Call by value is coping the value and manage it while Call by reference means referencing the value and then manage it.

Call by reference

Let’s see the example code first.

Before looking at the code, you should know about operator ‘&’

Reference means alias (like a nickname) for an object. This operator is used for call-by-reference type. This can be used to avoid the run-time impact of passing large number arguments by value which makes it more convenient. Also, Parameters, return values, and variables can all be defined as ‘references’.

In this code, x is reference type and it refers foo. So the value of foo and x will be changed the same like the picture below.

Call-by-reference Type

In C, this can be written using pointer.

But in this case, the operator ‘&’ on the line 4 is address-of operator which refers the address of the variable. It’s different from making the call-by- reference type! The operator ‘&’ of call-by-reference is used when it is declared.

Call by value

https://gist.github.com/9520d69616fd74110f65686f92eca918.git

In contrast, in call-by-value, the value of foo won’t be changed while the value of x will be 100.0 after returned.

Call-by-value type

So we learned about call-by-reference and call-by-value. It will be useful in C or C++ families. Thank you for reading.

--

--