Lecture 14
Cal l by Reference
Arguments can generally be passed to functions
in one of the two ways:
(a)
sending the values of the arguments
(b)
sending the addresses of the arguments
In the first method the ‘value’ of each of the
actual arguments in the calling function is copied into corresponding formal
arguments of the called function. With this method the changes made to the
formal arguments in the called function have no effect on the values of actual
arguments in the calling function. The following program illustrates the ‘Call
by Value’.
The output of the above program would be:
Note that values of a and b remain
unchanged even after exchanging the values of x and y.
In the second method (call by reference) the
addresses of actual arguments in the calling function are copied into formal
arguments of the called function. This means that using these addresses we
would have an access to the actual arguments and hence we would be able to
manipulate them. The following program illustrates this fact.
The output of the above program would be:
a = 20 b = 10
Note that this program manages to exchange the
values of a and b using their addresses stored in x and y.
Usually in C programming we make a call by
value. This means that in general you cannot alter the actual arguments. But if
desired, it can always be achieved through a call by reference.
Using a call by reference intelligently we can
make a function return more than one value at a time, which is not possible
ordinarily. This is shown in the program given below.
And here is the output...
Here, we are making a mixed call, in the sense,
we are passing the value of radius but, addresses of area and perimeter.
And since we are passing the addresses, any change that we make in values
stored at addresses contained in the variables a and p, would
make
the change effective in main( ). That is
why when the control returns from the function areaperi( ) we are able
to output the values of area and perimeter. Thus, we have been
able to indirectly return two values from a called function, and hence, have
overcome the limitation of the return statement, which can return only
one value from a function at a time.
Let’s
Examine Ourselves
What will be the output of the following
programs-
main(){
int a, *b,
**c, ***d, ****e;
a=10;
b=&a;
c=&b;
d=&c;
e=&d;
printf(“%d
%d %d”, a, a+*b,**c+***d+****e);
}
1 comments:
Very informative keep blogging.chemical overhaul
Post a Comment