Passing by reference vs. passing by value

Jose Salvatierra
School of Code
Published in
2 min readOct 6, 2016

When we call a method in a programming language, we can pass parameters to it. These normally are values that can be used within the method, and only exist inside it.

For example, take the following block of code (written in pseudocode, not in any specific programming language):

my_variable = 25define sum_to_variable(v):    v += 10    return vprint(my_variable)print(sum_to_variable(my_variable))print(my_variable)

What do you think this will print out to the console?

There are two options:

253525

Or

253535

Passing by value

In the first code example, the variable is passed by value. This means that in our method sum_to_variable, v is a new variable which contains the value of my_variable.

When we change v, this does not affect my_variable, because they are completely unrelated.

All we’ve done is put the value of my_variable inside v — essentially copying it.

Passing by reference

The second code example would be what happens if the variable is passed by reference. In this example, v does not contain the value 25. Instead, it contains a reference to the variable my_variable.

When we change the variable v, this changes my_variable. The number 25 is only stored inside my_variable — and nowhere else.

It’s all wrong

Although the rounds have many a time gone around the internet about passing by value and passing by reference, oftentimes programming languages all pass by value.

The myth (which I’ve been guilty of continuing) comes from the C principle of passing references as parameters. This is not the same as passing by reference!

In C you would have a variable such as the following:

int myVar = 125;

And, when passing it to a method, you could pass it like so:

myMethod(myVar);

Which would effectively pass its value. This is the “normal” way of passing parameters.

But, we could also do this:

myMethod(*myVar);

Which would pass a pointer to myVar. This is effectively “passing by reference”. However, there is a technical distinction to make:

We aren’t “passing by reference”. We’re passing a reference “by value”.

In the next post, I’ll talk about how Python handles argument passing, and how “passing by reference” and “passing by value” translate to Python.

--

--