Pointers And Functions
The arguments (or) parameters to the functions are passed in two
ways:
- Call by value.
- Call by reference.
Call by value:
In call by value, the values of the variables are passed. In
this value of variable are not affected by changing the value of
formal arguments
Program:
#include<stdio.h> #include<conio.h> void main() { int a=5, b=8; clrscr(); printf(“ before fn. Call a & b are %d & %d \n”, a, b); value(a, b); Printf (“after fn. Call a& bare %d & %d \n”, a,b); } void value(p, q) { int p, q; p++; q++; printf(“In fn., changes are %d & %d \n “, p, q); }
O/P:
Before fn.call a & b are 5 & 8.
In
fn., changes are 6, 9.
After fn. Call a & b are 5 &
8.
EXPLANATION:
Before calling the function
value (), the value of a=5 & b=8. The variables a&b are
passed as the parameter in the function value (). The values of
a & b are passed to ‘p’ and ‘q’. But memory locations are
different from the memory location of a & b. hence when the
values of ‘p’ & ‘q’ are incremented, there will be no effect
on the value of ‘a’ & ‘b’. So, after calling the function
‘a’ and ‘b’ are same as before calling the function and has the
value 5 & 8.
CALL BY REFERENCE
In call by reference, the addresses of the variables are passed.
When we pass addresses to a function, the parameters receiving
the addresses should be pointers. The process of calling a
function using pointers to pass the addresses of a variable is
known as ‘call by reference’.
PROGRAM:
#include<stdio.h> #include<conio.h> Void main() { int a=5, b=8; clrscr(); printf (“before calling function a and b are %d and %d \n”,a, b); ref (&a, &b); printf (“after calling the function a and b are %d & %d \n”,a,b); getch(); } void ref (p, q) Int *p, *q; { (*p)++; (*q)++; printf (“in function, changes are %d & %d \n”,*p,*q); }
EXPLANATION:
Before calling the function ref (), the
value of a=5, b=8. The address of the variables a and b are
passed as parameters in the function ref (). The address of a
and b are passed to p and q, which is a pointer variable. (*p)++
means value at address is incremented. So the value at address
of a, i.e., 5 is incremented, similarly (*q) ++ means value at
address of b i.e., 8 is incremented. Now the value *p=6, *q=9.
Here the address is not changed, but value at this address
is changed. Hence after calling the function the values of the
variables a and b are changed.