Return and Replace
00:00 One of the top best practices for mimicking pass by reference is with something called return and replace. You’ve actually seen this before in the lessons about the customized greetings, but let’s look at this in a new example.
00:14 A common pass by reference example is a function to square a variable, with the variable to retain that new value after the function is called. Here’s a simple C++ function to demonstrate that. The function takes an argument by reference and actually replaces that value with its square.
num is passed by reference. It is then multiplied by itself and saved back to the same variable. Nothing is returned. The side effect of changing the argument is the intent of the function.
main() function to try it out, we create a variable with the value
4, use that as the argument to pass by reference to the
squareRef() function, and then it displays the new value, which should be
01:37 The technique is called return and replace. Since the function can’t reassign the new value to the argument variable passed, you as the programmer must take the steps to make that happen, which means the function has to return the new value, and when calling the function, the return value needs to be saved back to that same variable.
So, here’s that same Python
square() function you saw in one of the earlier lessons. It returns the square of the argument provided. I’ve commented out the script you saw before, because I want to use this function interactively this time.
val has now been changed to
16. If a function is to modify multiple variables, just return the new values and unpack the tuple back into the desired variables, just like you saw with that greeting function from earlier.
Again, remember this returns a greeting personalized to the name provided as the first parameter and then increments—well, adds
1 to the counter, which should be saved back to the same variable passed as an argument, to create the effect of incrementing it by
So, let’s create our
count variable. Right now, we’ve called that function zero times. When we call it, we get two values back in a tuple, and we can unpack it simply by assigning each one to a separate variable.
count, we want to mimic pass by reference with return and replace, so we pass it as the parameter to be modified, and when it’s returned, we replace that variable with its new value.
Become a Member to join the conversation.