Can anyone explain me the diffrence between call by reference and a call by value
Printable View
Can anyone explain me the diffrence between call by reference and a call by value
see for yourself.... compile and run this:-
Code:#include <stdio.h>
#include<stdlib.h>
void byvalue (int x)
{
x+=5; // x=x+5
printf("Value of x in byvalue is %d\n",x);
}
void byref(int*x)
{
(*x)+=5;
printf("Value of x in byref is %d\n",(*x));
}
int main()
{
int x=5;
int* y=&x;
byvalue(x);
printf("x in main is %d\n",x);
byref(y);
printf("x in main is %d\n",x);
system("PAUSE");
return 0;
}
a call by value passes only the-value-of a variable, while a call by reference passes a reference (address usually) to a variable so that it's value can be altered
Passing by reference is faster than passing by value (and it saves a little bit of memory), but when passing by value, you can't accidently change the value of a variable.
When you pass by value, a copy of the object is created in the called function and placed on that functions memory stack, whereas references use an address to the original value in the caller, this requires a pointer to be created but not a whole copy of the object.