0
Why formal parameter affects call by reference but not value..?
2 Antworten
+ 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);
+ 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