Pass by Reference
00:05 Pass by reference means that the function receives a reference—link, pointer—to the argument passed as a parameter. The parameter value doesn’t receive a copy of that value. Instead, the parameter variable actually refers to the same piece of memory that the argument referred to. They become two different names for the same object.
Recall in the example from the last lesson, how the array of numbers—
2.0, and so on to
7.0—was assigned to the variable
numbers, then that array was passed to the function parameter variable
00:43 In C++, passing an array like this would have used the mechanism pass by reference. Let’s take a look at how that works in memory. I’ll use that same simplified model of memory to demonstrate what happens with pass by reference. First, before it’s even assigned a name, a space in memory is created to store the array. Because an array and other complex objects have different memory needs, they’re not stored directly with any variable names they’re assigned to.
The location of the array is given some internal notation. I’m just making something up for the purposes of this example,
_array1. The actual process often involves memory addresses in some way, and I didn’t need to get that detailed with this example.
02:22 So again, pass by reference means the parameter variable is given a reference, not the value, to the argument provided. This has some interesting consequences. For example, let’s say you write a function that modifies the parameter variable Then, those changes will remain after the function ends and will be noticed when you use the argument variable in some way.
03:10 Well, once programmers realized that you could impact an argument through a function when pass by reference is being used, they came up with all sorts of good reasons to do so, and here are a couple of the biggest ones.
03:33 Many programming languages allow for only one actual return value. So you could pass by reference another argument, then assign that argument to something that could be considered a second return value, in addition to what the return statement would give back to the calling environment.
03:51 Notice, we’re still not talking about Python. Python doesn’t use pass by reference either. We’re almost there, but I want to show you what pass by value and pass by reference look like in C++ and then look at what happens when we compare those behaviors to what Python does. You’ll see that comparison in the next lesson.
Become a Member to join the conversation.