Thursday, July 9, 2009

Explain call by value and call by reference in c++?

Call by value:- Passing only the values so that only copy of the value is sent to functions


Eg:


int main()


{


int a=10,b=20,c;


c=add(a,b);


cout%26lt;%26lt;c;


return 0;


}


int add(int x,int y) // copy of values ie a,b is received here


{


int z;


z=x+y;


return x;


}


call by Reference:


the address of the value is passed and since address is passed the original value will change since address is modified


Eg:


int main()


{


int a=10,b=20,c;


c=add(%26amp;a,%26amp;b); // address is passed


cout%26lt;%26lt;c;


return 0;


}


int add(int *x,int *y) // address locatin is received


{


int z;


z=x+y;


return x;


}


is it ok!


Or Wanted more

Explain call by value and call by reference in c++?
in call by value the actual parameters are mapped to the formal parameters an dany changes made to the formal parameters will not be affected to the actual parametrers bcoz we are just copying the parameters


but in call by reference any changes made to the formal parameters will effect the actual parameters bcoz in call by reference the address is passed as a parameters
Reply:In call by value the values are called in the subroutine which are in the main program by saving them in a memory called stack which stores the values used in the main program %26amp; by using appropriate commands we can access them in the subroutine.


In call by reference, the address of the variable is used in the subroutine to access them.
Reply:For all your C++ doubts refer


http://cetus-links.org/oo_c_plus_plus.ht...
Reply:in call by value actual parameters are passed. so a new memory area is created for the passed parameters in local memory(stack). so the actual parameters are not modified here.





in call by reference we pass address of the variables. so the parameter passed is referenced to the original variable. so any changes made inside the function reflects in change of original variable as memory area is same


No comments:

Post a Comment