Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying arguments 'passed by value' inside a function and using them as local variables

I have seen some code in which the arguments passed to the function by value was being modified or assigned a new value and was being used like a local variable.

Is it a good thing to do? Are there any pitfalls of doing this or is it Ok to code like this?

like image 839
Jay Avatar asked Jan 21 '10 11:01

Jay


People also ask

When arguments are passed by value the function works with the original arguments in the calling program?

Ans- When passing data by value, the data is copied to a local variable/object in the function. Changes to this data are not reflected in the data of the calling function.

What is called when an object is passed by value into a function?

Pass By Value: In Pass by value, function is called by directly passing the value of the variable as an argument. So any changes made inside the function does not affect the original value. In Pass by value, parameters passed as an arguments create its own copy.

Does pass by reference allow modification of a function argument?

Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in.

When you pass by value altering actual parameters is possible?

Pass by value means that a copy of the actual parameter's value is made in memory, i.e. the caller and callee have two independent variables with the same value. If the callee modifies the parameter value, the effect is not visible to the caller.


2 Answers

Essentially, a parameter of a function is a local variable, so this practice is not bad in principle.

On the other hand, doing this can lead to maintenance headaches. If another programmer comes along later, he might expect the variable to hold the passed in value, and the change will cause a bug.

One justification for reusing the variable is for a misguided notion of efficiency of memory usage. Actually, it can't improve efficiency, and can decrease it. The reason is that the compiler can automatically detect if it is useful to use the same register for two different variables at two different times, and will do it if it is better. But the programmer should not make that decision for the compiler. That will limit the choices the compiler can make.

The safest practice is to use a new variable if it needs a new value, and rely on the compiler to make it efficient.

like image 133
uncleO Avatar answered Oct 03 '22 01:10

uncleO


No problems at all that I can think of. The arguments will either be placed in the current stack frame or in registers just like any other local variable. Make sure that the arguments are passed by value, however. In particular, arrays are passed by reference.

like image 43
Mick Avatar answered Oct 03 '22 01:10

Mick