Computer Science Canada passing by reference vs passing by memory |
Author: | Horus [ Sat Dec 13, 2008 9:26 pm ] |
Post subject: | passing by reference vs passing by memory |
According to my teacher, the difference between passing by reference and passing by memory is that when you use passing by reference, the variable you passed to the function/procedure can be modified by the function/procedure. and passing by memory couldn't. However when you are passing by memory, it creates a copy of each of the variables inside the function/procedure which takes more memory. So now, isn't passing by reference always better? because the variables could modify the main program and saves a bit of memory. and if you really need to change the values inside the function/procedure without affecting the main program, you can always create local variables instead. I don't see the point of using passing by memory. |
Author: | Tony [ Sat Dec 13, 2008 9:47 pm ] |
Post subject: | RE:passing by reference vs passing by memory |
the term is pass by value (not by "memory"). The short answer is that pass-by-value is safer. The longer answer involves an example where you might want to pass a result of one function as an argument to a different function. |
Author: | gianni [ Sun Dec 14, 2008 4:27 am ] | ||
Post subject: | RE:passing by reference vs passing by memory | ||
Also it is not always desirable to modify a variable directly, especially in cases where the variable will be reused or the initial variable data is expected. For example, in the following, it would not be useful if the port method modified the host variable:
|
Author: | SJ [ Sun Dec 14, 2008 10:11 am ] |
Post subject: | RE:passing by reference vs passing by memory |
for example, when you write some recursion to a certain depth, like void rec (int currentDepth, int maxDepth) {} you'd want to pass maxDepth as a reference (or a global variable) and currentDepth by value. it really depends on what you are doing. |
Author: | md [ Sun Dec 14, 2008 12:13 pm ] |
Post subject: | Re: RE:passing by reference vs passing by memory |
SJ @ 2008-12-14, 10:11 am wrote: for example, when you write some recursion to a certain depth, like
void rec (int currentDepth, int maxDepth) {} you'd want to pass maxDepth as a reference (or a global variable) and currentDepth by value. it really depends on what you are doing. Definitely not glboal - unless it was a constant. If you passed it by reference in C or C++ you'd want to specify it as a constant too. Passing by reference is only a good idea if you want to change the variable inside your function (which is not usually a good idea) or if you have some way of marking it as a constant so you can't change it even accidentally. |