C Call by Value and Call by Reference

There are two methods to pass data into functions, i.e. call by value and call by reference.

Call by Value

In call by value method, the value of the actual parameters are copied into the parameters. No change is reflected to the actual parameters if the value of the parameter is modified. In call by value, different memory is allocated for actual and formal parameters since the value of the actual parameter is copied into the formal parameter.

Example Code

#include<stdio.h>  
void modify(int val)
{
	val = 10;
	printf("Passed Value: %d\n",val);
}

int main(void)
{
	int x = 5;
	
	printf("Value of x before function call: %d\n",x);
	modify(x);
	printf("Value of x after function call: %d\n",x);
	
	return 0;
}

Output

Value of x before function call: 5
Passed Value: 10
Value of x after function call: 5

Call by Reference

In call by reference, address of the variable is passed. Any changes made here will be reflected to the actual parameters. No extra memory is allocated in call by reference since the reference variable stores the address of the variable. In C, call by reference is implemented by passing the value of the pointer. Also, in C, the arrays are passed to the fuction by sending their address of the first block. Hence, any changes made into the array inside the fuction is also reflected back.

Example Code

#include<stdio.h>  
void modify(int *ptr)
{
	*ptr = 10;
	printf("Passed Value: %d\n",*ptr);
}

void modifyArray(int arr[])
{
	arr[0] = 5;
}

int main(void)
{
	int x = 5;
	
	int array[] = {1,2,3};
	
	printf("Value of x before function call: %d\n",x);
	modify(&x); //pass by reference   
	printf("Value of x after function call: %d\n",x);
	
	printf("Value of array[0] before function call: %d\n",array[0]);
	modify(array); //passing address of array[0]   
	printf("Value of array[0] after function call: %d\n",array[0]);
	
	return 0;
}

Output

Value of x before function call: 5
Passed Value: 10
Value of x after function call: 10
Value of array[0] before function call: 1
Passed Value: 10
Value of array[0] after function call: 10

Trending

C Programming

Remember to follow community guidelines and don't go off topic.