0
487views
What is Call by Value and Call by Reference?
1 Answer
0
0views

In general, the parameter passing in C is by value rather than by address, but passing the parameter by value generally creates ambiguity. So, the technique of call by reference came in to picture which maintains persistence in the data stored by the variables. To understand consider the example:

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap (int a, int b);
clrscr();
printf("Enter two numbers:");
scanf("%d %d",&a,&b);
printf("The values of a and b in the main function  before calling the swap function are %d and %d\n",a,b);
swap(a,b);
printf("The values of a and b in main function after    calling the swap function are %d and %d\n",a,b);
getch();
}
void swap (int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
printf("The values of a and b in the swap function after swapping are %d and %d\n",a,b);
}

In the Call by Reference, calling function the address of the data element and not the value stored in that data element. Such calls to function may look like swap (&a,&b), now here the addresses of the variable a and b are passed to the function.

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap (int *p1, int *p2);
clrscr();
printf("Enter two numbers:");
scanf("%d %d",&a,&b);
printf("The values of a and b in the main function  before calling the swap function are %d and     %d\n",a,b);
swap(&a,&b);
printf("The values of a and b in main function after    calling the swap function are %d and %d\n",a,b);
getch();
}
void swap (int *p1, int *p2)
{
int temp;
temp=*p1;
*p1=*p2;
*p2=temp;
printf("The values of a and b in the swap function  after swapping are %d and %d\n",*p1,*p2);
}
Please log in to add an answer.