Saturday, 27 December 2014

CALL BY REFERENCE FUNCTION EXAMPLE

The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument.
To pass the value by reference, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following functionswap(), which exchanges the values of the two integer variables pointed to by its arguments.

#include<stdio.h>
#include<conio.h>
 void fun1(int *,int *);
void main()
{
int a,b;
clrscr();
printf("\n   CALL by REFERENCE\n");
printf("Enter values of A and B\n");
scanf("%d%d",&a,&b);
printf("\nfrom main before call\n");
printf("\nA = %d ,B = %d",a,b);
fun1(&a,&b);
printf("\nfrom main ,back after fun1\n");
printf("\nA = %d ,B = %d",a,b);
getch();
}

void fun1(int *x,int *y)
{
 printf("\nfrom fun1 before swap\n");
 printf("\nX = %d , Y = %d",*x,*y);
  // swap without 3rd variable
 *x=*x+*y;
 *y=*x-*y;
 *x=*x-*y;
 printf("\nfrom fun1 after swap\n");
 printf("\nX = %d , Y = %d",*x,*y);
}

No comments:

Post a Comment

Tell Us What You've Got...