Call by Reference :
Definition: It is a calling function by address of variable.
Example for Call by reference:
#include<iostream>
int main()
{
int a=10,b=20;
void display(int *, int *);
display(&a, &b);
return 0;
}
void display(int *x, int *y)
{
printf("\n %d %d ",*x, *y);
}
Swapping
two variables using call by reference function:
#include<iostream>
int main()
{
int a=10,b=20;
void swap(int *, int * );
printf("\b
Before swap ");
printf("\n
%d %d",a,b);
swap(&a,&b);
printf("\n
After swap");
printf("\n
%d %d",a,b);
return 0;
}
void swap(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
O/p:
Before
swap
10 20
After swap
20 10
Reason:
In
the above example, swap() function is call by reference, its arguments are
pointers, which receives address of variables. These arguments works with actual
copies ( passing variable).
Hence Swapping operation takes place on
original copies through address ( pointers )
In call
by reference function, the
changes made on arguments will be reflected on actual variables ( passing
variable);
1 Comments
Yes sir the programs written here are correct and working in the compiler you provided.
ReplyDelete