C - Call by Reference in Functions

<<Previous

Next >>





In this method, the address of the variable is passed to the function. So in this case, both actual and formal parameter use the same address space. If any changes made to the formal parameter inside the function, that change will reflect on the original value of the actual parameter. While calling,parameter name is being passed along with address operator in function call.

Let's see the example program using call by reference.

#include<stdio.h>


int multiply(int *m,int *n);
void main()
{
	int a = 1, b  = 2, c;

	printf("The value of a and b: %d\t%d", a,b);
	c = multiply(&a,&b);
	printf("\nThe value of a and b after function call: %d\t%d ", a,b);
	printf("\nThe multiplication result: %d",c);
	getch();
}

int multiply(int *m, int *n)
{
	int result;
	*m = *m + 2;
	result = *m * *n;
	return(result);

}

Here the copy of actual parameter values (a & b) are passed to the function call. when you compile and run the above program, you will get the following output.



The result shows that called function changed the value of one of the parameters "m". This has reflected on the original value of actual parameter "a".


<< Previous

Next >>