+ 2

What is call by reference and how it works? Please explain.

Please explain how call by reference works in function.

2nd Mar 2017, 4:28 AM
zeeshan
zeeshan - avatar
2 Respuestas
+ 9
Functions normally receive arguments call-by-value. A copy of the values you use are sent to it, not the variable itself. And so, its value won't change. Ex: int main() { int x = 7; doubleNum(x); //Sends a copy of x's value of 7 cout << x; //Only the copy was modified - x is still 7. } void doubleNum(int in_x) { in_x *= 2; } //Doubles 7 to 14 Pass-by-reference, on the other hand, is sending over the variable's locations in memory, and so the function is free to modify it directly. That change will persist even when the function ends. In order to do this, you need to use the operator & to get the address of the variable, and have a pointer in the function to receive it. Ex: int main() { int x = 7; doubleNum(&x); //Sends x's memory address cout << x; //The modification below is reflected here - x is now 14. } void double(int* xPtr) {*xPtr *= 2; } //*xPtr holds the memory address. Doubles 7 to 14
2nd Mar 2017, 5:00 AM
Tamra
Tamra - avatar
+ 4
suppose it teacher gives u a sheet of paragraph written in it and u do correction on it and return to teacher,,,, similarly by call by reference u pass address of variables then their occurs some operations on it and then result is returned,☺... in call by value u do corrections but not on the given sheet but u copy the information then do corrections on it similarly operations are done on copied values and no change reflect ed back
2nd Mar 2017, 6:49 AM
Sakshi Verma
Sakshi Verma - avatar