References and Values

What’s the difference?

Long story short:

Variables reference a value.

or in code

`reference = value;`

So what does it mean when we say a function passes by reference vs passes by value?

Consider this code.

`int x = 1; // Assigns 1 to variable x. `
`function increment(x): {x = x+1;} // Adds 1 to x. `
`increment(x); // Computes increment on x. print(x); // Prints x.`

Whether a function passes by value or passes by reference makes all the difference in this short program.

Pass by reference

The pass by reference does what you think it does. The increment function increases the value of the x variable by 1.

So the print line outputs 2.

Things are less intutive when a function passes by value.

Pass by value

Let’s now suppose that increment is a function that passes by value. If I run the code, what happens?

What happens is that the function increment evaluates on the value 1. Inside however, the line

`x = x+1;`

creates a new variable x, which is a temporary variable for the sake of being used in the function alone. Beyond that, x means what it used to mean, a reference to the number 1.

Inside the function, x is a reference to what x was outside the function (the number 1), plus 1. So now x is 2, but only for the duration of the function’s computation.

Since the print line isn’t inside the function, it refers to the old x that was outside of the increment function, and the old x refers to 1. So the increment function as it is does pretty much nothing for all practical purposes if it passes by value.

Since the increment function does nothing, the print line outputs 1, the original value of x.

Understanding whether you’re passing by value or reference is essential to programming. Some languages pass by value as default and others pass by references. Most popular languages however, do a combination of both.

The easiest way to remember the distinction between the two is simply what I stated at the start of this article. It’s usually what helps me remeber it.

Variables reference a value.

That is, variables are references, and they point to a value. So it makes sense when we pass by value in a function, that nothing happens to the reference of the value (ie. the variable). However, when we pass by reference, a function can change the properties of the value associated to the variable.

Like what you read? Give Discipliberal a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.