call by reference program in c
C Programming

Call By Reference Program in C

Call By Reference Program in C

The difference between the Call by Value and the Call by Reference method is generally asked in the University Examination and also asked in technical interview.

The difference between call by value and call by reference is that in the case of the call by value method, if we change the value of formal arguments, then the value of actual arguments does not change.

We have already discussed Call the Value Program in C and concept in previous post.

In the case of call by reference method, the value of actual arguments changes by changing the value of formal arguments because, in the case of call-by-reference, we pass the address of actual arguments.

We will see it with the help of the following program.

Call by Reference Program in C

In call by reference program in C we use the concept of pointers. We pass the pointer parameter to function.

Call by Reference Program in C is given below

#include<stdio.h>

void swap(int *x, int *y);   // Declare a Swap function

int main()
{

int m=22;

int n=44;

printf(“before swap m=%d and n=%d\n”,m,n);

swap(&m,&n);

printf(“after swap m=%d and n=%d\n”,m,n);

return 0;

}

void swap(int *x, int *y)
{

printf(“value of x=%u value of y =%u\n”,x,y);

printf(“Before swap value stored at address x=%d and value stored at address y =%d\n”,*x,*y);

int temp;

temp=*x;

*x=*y;

*y=temp;

printf(“value of x=%u value of y =%u\n”,x,y);

printf(“After swap value stored at address x=%d and value stored at address y =%d\n”,*x,*y);

}

In above program since x and y are the Pointer type variables so x and y are the memory address of variable m and n because in function calling address of m and n is passed.

Since x and y are the address so address remain same after swap but value stored at address x  and address y will be swap.

Since here we are swapping the value of stored at address x and y it means we are swapping the value formal arguments so after value of actual argument m and n will also be swapped.

Output

call by reference

When we execute the above program then the output is displayed. From the output it is cleared that value of  both actual and formal argument have been changed .

Conclusion and Summary

  • In this tutorial we have explained the concept of call by reference program in C.
  • Difference between call by value and call by reference is also discussed here in this tutorial.

 

Leave a Reply

Your email address will not be published. Required fields are marked *