0

Why formal parameter affects call by reference but not value..?

19th Jul 2017, 2:02 PM
Rahul.R
Rahul.R - avatar
2 Réponses
+ 2
In call by value, we pass the data of the variable into the function, and the function creates a temporary copy for its use. Thus manipulating that copy doesn't affect the real value, as it was never even used inside the function, as the copy is made before invoking of the function. Thus in call by value, one can even put something like these in parameters: cout<<pow(2,2); //Prints 4. Now, on adding a & sign before the parameter, the compiler no longer gets the data from the variable passed during call, rather, it gets the address of the variable passes and manipulates the value at that address... Thus, the user is allowed to choose the address to store the manipulated version, and thus, if you pass a variable, the variable gets affected, as the address is the same, even after you exit from the function... Thus, doing this in a call by reference function is not permitted: swap(2,3);
20th Jul 2017, 3:27 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 1
When you pass by value, the parameter is copied in temporary one and all operations inside the function affects that temporary copy, not the actual one
19th Jul 2017, 2:53 PM
soman