2014-01-31 - Passing Parameters
C is an old but very influential programming language. In C there are two ways to pass parameters to functions, by value and by reference. Pass by value means the parameter passed to a function is a copy of the original value while pass by reference means the parameter is a pointer to the original value. The main difference is that pass by reference allows you to modify the original value. If the function is called with a variable passed by reference then any changes the function makes to the variable will be visible to the caller when the function returns.
Jump forward a few years to the rise of object oriented programming languages. In these languages most functions use pass by value but there’s a bit of an issue. In object oriented languages the object variable contains a reference to the object’s data and not the actual data. So when you pass an object by value the system is actually making a copy of that object’s reference. The original reference and the copied reference still point to the same data. This means that even though you are using pass by value you can still change the original variable’s data. If you had an employee object with name “A” and you passed it into a function that changes its name to “B” once that function returns the original employee object would also have the name “B”.
That is as long as you don’t change the reference. Changes to the function’s variable affect the original variable because they point to the same thing. If you change the thing the function variable is pointing to then this is no longer the case. This can happen if you create a new object or perform an action that creates a new object and assign the result to the function’s variable.
Comments: