Pass by Value
Since I don’t have a way to run C++ code interactively, I’ll have to write something like a script to test it. In C++, we call that a main function. You can see inside this main function that I create a variable
I’m saying it’s an integer, but C++ can make it a decimal value when the function is called. The next line is C++’s unique output statement. It begins with the word
cout. Then, with less than sign type of arrows (
<<), we indicate what we want printed.
C++ uses something called pass by value for simple types. I can demonstrate that with a very simplified model of memory. When the main function is run, a specific place in memory is designated to hold the value of the variable
val, which has a value of
4. When the function is called, a new place of memory is made to hold the value of
num, and then the value of
4 is copied from
val to that memory location.
That’s what we mean by “pass by value.” The value is copied from the argument to the parameter. When the function finishes running, the memory for
num is removed but the memory location for
val remains until the program itself quits running.
Now, I know this is a very simplified explanation of how memory works, but hopefully it illustrates the point that I want to make. The value of
4, is copied to be the value of
num. “Pass by value.” Pass by value works for simple types, but not for more complicated structures.
03:19 Here is a simple C++ function to find the mean of a collection of numbers—in this case, provided in something called an array. In C++, we have to pass the array and the size of the array as arguments to this function.
I won’t go into the details of how this function works. Just know that it loops through the collection, accumulating the sum as it goes. Then it divides that by the size of the collection. Below it, I have a main function that creates an array called
numbers and then passes that array and its size to the
05:12 And even if memory size isn’t a problem, there’d be a lot of computation time to copy the entire array from one location in memory to another. So, pass by value might not be the best mechanism for more complicated types. This is where pass by reference comes in.
Become a Member to join the conversation.