Wednesday, September 29, 2010

Call by Value, Call by Reference

In a computer language, there are two ways that arguments can be passed to a
subroutine. The first is known as call by value. This method copies the value of an argument into the formal parameter of the subroutine. In this case, changes made to
the parameter have no effect on the argument.
Call by reference is the second way of passing arguments to a subroutine. In this
method, the address of an argument is copied into the parameter. Inside the subroutine,
the address is used to access the actual argument used in the call. This means that
changes made to the parameter affect the argument.
By default, C/C++ uses call by value to pass arguments. In general, this means that
code within a function cannot alter the arguments used to call the function. Consider
the following program:
#include <stdio.h>
int sqr(int x);
int main(void)
{
int t=10;
printf("%d %d", sqr(t), t);
return 0;
}
int sqr(int x)
{
x = x*x;
return(x);
}
In this example, the value of the argument to sqr() , 10, is copied into the parameter
x. When the assignment x = x*x takes place, only the local variable x is modified. The
variable t, used to call sqr() , still has the value 10. Hence, the output is 100 10.
Remember that it is a copy of the value of the argument that is passed into the
function. What occurs inside the function has no effect on the variable used in the call.

No comments:

Post a Comment