Difference between Call by Value and Call by Reference in C

Here you will learn about difference between call by value and call by reference in C.

There are two different ways of passing values to functions: call by value and call by reference. They are also called as pass by value and pass by reference.

 

Call by Value in C

In call by value method a copy of actual parameters is passed which is stored in formal parameters.

Actual Parameters: The parameters that are passed while calling the function are called actual parameters.

Formal Parameters: The parameters that hold the values of actual parameters are called formal parameters.

In call by value method, if any changes are done in formal parameters then actual parameters are not changed.

Let’s take an example of call by value in C language.

Example:

#include<stdio.h>

void fun(int x)
{
	x=x+5;
}

int main()
{
	int a=10;
	printf("Before calling\na=%d",a);
	fun(a);
	printf("\n\nAfter calling\na=%d",a);
	
	return 0;
}

 

Output:

Call by Value in C

As you can clearly see in output that after calling the function and doing changes in formal parameter x, the actual parameter a is not changed.

 

Call by Reference in C

In call by reference method, reference or address of actual parameters is passed which is stored in formal parameters.

If any changes are done in formal parameters then actual parameters are also changed.

Let’s take an example of call by reference in C language.

Example:

#include<stdio.h>

void fun(int *x)
{
	*x=(*x)+5;
}

int main()
{
	int a=10;
	printf("Before calling\na=%d",a);
	fun(&a);
	printf("\n\nAfter calling\na=%d",a);
	
	return 0;
}

 

Output:

Call by Reference in C

You can clearly see in output that after calling the function and doing changes in formal parameter x, the actual parameter a is also changed.

 

Difference between Call by Value and Call by Reference in C

 

Difference between Call by Value and Call by Reference in C

S. No. Call by Value Call by Reference
1. A copy of actual parameters is passed into formal parameters. Reference of actual parameters is passed into formal parameters.
2. Changes in formal parameters will not result in changes in actual parameters. Changes in formal parameters will result in changes in actual parameters.
3. Separate memory location is allocated for actual and formal parameters. Same memory location is allocated for actual and formal parameters.

 

If you have any doubts related to above tutorial then you can ask it by commenting below.

15 thoughts on “Difference between Call by Value and Call by Reference in C”

Leave a Comment

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