0

What is difference between call by value & call by reference in c++

4th Dec 2016, 2:22 PM
himanshi
2 odpowiedzi
+ 2
call by value passes d copy of a value in a variable which means it wont modify/change the original value of a variable while call by reference passes d orginal value of a variable. which means it will modify/change the original value of a variable. void printValue(int ); void printRef (int*); int val = 5; int ref = 7; int main () { printValue(val); printRef (&ref); cout << val; //prints 5 cout << ref; //prints 10 return 0; } void printRef(int *r) { ref = r + 3; } void printValue(int v) { val = v + 3; }
5th Dec 2016, 2:22 PM
Franky BrainBox
Franky BrainBox - avatar
0
In call by value the parameters are passed duplicates or copies of it are created( formal parameters) so any change to these variables in the function wouldnt be reflected back where as in call by reference method you pass the variables addresses& so any change is made it happens in the passed address thus change in values of function reflected back. example: void sum(int a,int b) { a=a+b; b=a+b; cout<<a<<b;} void sumr(int &a,int &b) { a=a+b; b=a+b;} void main() { int x=1,y=2; sum(x,y); cout<<x<<y; // output 1 and 2 ( callbyvalue) sumr(x,y); // call by reference cout<<x<<y; // output 3 and 5 (changed)}
4th Dec 2016, 4:36 PM
kv ajay
kv ajay - avatar