C Language



Admission Enquiry Form

  

Call by Value and Call by Reference in C

What is Call by Value and Call by Reference in C?

Call by Value:

In call by value, a copy of actual arguments is passed from calling function to the formal arguments of the called function. If we made any change to the formal arguments in the called function then their will not have any effect on the values of actual arguments in the calling function.We can not modify the value of actual arguments of calling function in call by value.

Example Using Call by Value:

#include<stdio.h>
#include<conio.h>
int num1,num2,res;
void main()
{
void sum(int,int); //declaration of function
printf("\nCalling sum fun");
printf("\nEnter two no's");
scanf("%d%d",&num1,&num2);
sum(num1,num2); //call by value
printf("\n\n Now again in main()");
printf("\nValue of num1 is %d",num1);
printf("\nBye");
}//end of main

                 void sum(int n1,int n2)   //body of fun
{
res=n1+n2;
printf("\nResult is %d",res);
n1=500;
printf("\nValue of n1 is %d",n1);
}


Output

Calling sum fun
Enter two no's
100
200

Result is 300
Value of n1 is 500

Now again in main()
Value of num1 is 100
Bye




Call by Reference:

In call by reference, the address of actual arguments from calling function is passed to formal arguments of called function.So, in this case formal arguments will be pointer variable,those can hold the address of actual arguments.Now by accessing the addresses of actual arguments we can change the value of actual arguments from the called function.
So, we can say that changes to actual arguments of calling function is possible from called function.

Example Using Call by Reference:

#include<stdio.h>
int num1,num2,res;//external variables
void main()
{
int sum(int*,int*); //declaration of function
printf("\nCalling sum fun");
printf("\nEnter two no's");
scanf("%d%d",&num1,&num2);
res=sum(&num1,&num2);   //call by reference
printf("\n\n Now again in main()");
printf("\nResult is %d",res);
printf("\n Value of num1= %d",num1);
printf("\nBye");
}//end of main

                 int sum(int *n1,int *n2)   //body of function
{
res=*n1+*n2;
*n1=500;
printf("\n Value of *n1= %d",*n1);
return(res);
}


Output

Calling sum fun
Enter two no's
10
20

Value of *n1= 500

Now again in main()
Result is 30
Value of num1= 500
Bye