Monday, 12 September 2011

call by reference swap program

Q. what is calling by reference? How it is different from call by value? Write a C function to swap two given numbers using call by reference mechanism.

Ans.

When an argument is passed by reference, the caller actually allows the called function to modify the original variable's value.

  • Sends the address of a variable to the called function.
  • Use the address operator(&) in the parameter of the called function.
  • Anytime we refer to the parameter, therefore we actually referring to the original variable.
  • If the data is manipulated and changed in the called function, the original data in the function are changed.
/*swap function to interchange values by call by reference*/
#include<stdio.h>
#include<conio.h>
void swaping(int *x, int *y);
int main()
{
 int n1,n2;
 printf("Enter first number (n1) : ");
 scanf("%d",&n1);
 printf("Enter second number (n2) : "); 
 scanf("%d",&n2);
 printf("\nBefore swapping values:");
 printf("\n\tn1=%d \n\tn2=%d",n1,n2);
 swaping(&n1,&n2);
 printf("\nAfter swapping values:");
 printf("\n\tn1=%d \n\tn2=%d",n1,n2);
 getch();
 return 0;
}
void swaping(int *x, int *y)
{
  int z;
  z=*x;
  *x=*y;
  *y=z;
}

/***************** OUTPUT **************/
call by reference swap C program
Swap using call by reference

No comments:

Post a Comment