Call by value and call by reference
There are two way through which we can pass the arguments to the function such
as call by value and call by reference.
1. Call by value
In the call by value copy of the actual argument is passed to the formal argument
and the operation is done on formal argument.
When the function is called by ‘call by value’ method, it doesn’t affect content of
the actual argument.
Changes made to formal argument are local to block of called function so when the
control back to calling function the changes made is vanish.
Example:
main()
{
int x,y;
change(int,int);
printf(“enter two values:\n”);
scanf(“%d%d”,&x,&y);
change(x ,y);
printf(“value of x=%d and y=%d\n”,x ,y);
}
change(int a,int b);
{
int k;
k=a;
a=b;
b=k;
}
Output:
enter two values: 12
23
Value of x=12 and y=23
2. Call by reference
Instead of passing the value of variable, address or reference is passed and the
function operate on address of the variable rather than value.
Here formal argument is alter to the actual argument, it means formal arguments
calls the actual arguments.
Example:
void main()
{
int a,b;
change(int *,int*);
printf(“enter two values:\n”);
scanf(“%d%d”,&a,&b);
change(&a,&b);
printf(“after changing two value of a=%d and b=%d\n:”a,b);
}
change(int *a, int *b)
{
int k;
k=*a;
*a=*b;
*b= k;
printf(“value in this function a=%d and b=%d\n”,*a,*b);
}
Output:
enter two values: 12
32
Value in this function a=32 and b=12
After changing two value of a=32 and b=12
So here instead of passing value of the variable, directly passing address of the
variables. Formal argument directly access the value and swapping is possible even
after calling a function.