Anonymous

What Is Call By Value And Call By Referance?

2

2 Answers

Azhar Mehmood Profile
Azhar Mehmood answered
There are two ways of passing arguments/parameters to a function. One method is Call by Value and the other method is Call by Reference.
Call by Value: in the Call by Value the programming is sending the copy of an argument/parameter to a function. Programmer is not passing the actual variable. Since only the copy of the variable is passed to the function therefore any changes/modifications made within a function don't affect the variable and the variable value remains the same after the function call.
The following example will clarify it;
Suppose a = 2 before the function call
Void function (int a)
{
a = a + a;
a = a – 5;
}
Since only a copy of variable "a" is passed to the function that's why even after the function call value of a will remain 2.
Call by Reference: in the call by Reference the address of the argument/parameter is passed to the function. In simple words the actual variable or a pointer is passed to the function and variable value can be changed/modified within a function
For example; suppose a = 2 before function call
After passing this value to a function like
Void function(int &a)
{
*a = *a + *a;
*a = *a – 5;
}
The value of a will become "1" after calling this function.
Anonymous Profile
Anonymous answered
The arguments passed to function can be of two types namely

1. Values passed
2. Address passed

The first type refers to call by value and the second type refers to call by reference.

For instance consider program1

main()
{
int x=50, y=70;
interchange(x,y);
printf(“x=%d y=%d”,x,y);
}

interchange(x1,y1)
int x1,y1;
{
int z1;
z1=x1;
x1=y1;
y1=z1;
printf(“x1=%d y1=%d”,x1,y1);
}

Here the value to function interchange is passed by value.

Consider program2

main()
{
int x=50, y=70;
interchange(&x,&y);
printf(“x=%d y=%d”,x,y);
}

interchange(x1,y1)
int *x1,*y1;
{
int z1;
z1=*x1;
*x1=*y1;
*y1=z1;
printf(“*x=%d *y=%d”,x1,y1);
}

Here the function is called by reference. In other words address is passed by using symbol & and the value is accessed by using symbol *.

The main difference between them can be seen by analyzing the output of program1 and program2.

The output of program1 that is call by value is

x1=70 y1=50
x=50 y=70

But the output of program2 that is call by reference is

*x=70 *y=50
x=70 y=50

This is because in case of call by value the value is passed to function named as interchange and there the value got interchanged and got printed as

x1=70 y1=50

and again since no values are returned back and therefore original values of x and y as in main function namely

x=50 y=70 got printed.

Answer Question

Anonymous