Call by value and Call by reference in c

What is a Function?

Function is the group of statements which performs specific task.

int add(int m, int n)
{
  int c;
  c=m+n;
  printf("value is %d \n",c);
}

The above add() function is written to perform addition operation.


Call by value and call by refernce in c programming language

What is Call by value?

In Call by value actual parameters are being passed to a function by caller function.

If values are being changed in the callee function while executing it, actual values of variable in caller function is not being affected.

Temporary memory is allocated, values are copied to temporary variables then passed to the callee function. This temporary variable refers to formal parameter.

Actual parameter is passed while calling a function. Formal parameter is the parameter in definition of function.

C program to illustrate call by value

// C program to illustrate call by value
#include<stdio.h>
int add(int a,int b)
{
  int c;
  c=a+b;
  printf("result is %d \n",c);
  return c;
}
int main()
{
 int x=5,y=6;
 add(x,y);
 printf("x=%d,y=%d \n",x,y);
 return 0;
}

Output

Call by value program

Code explanation

In the above program, function add is performing an addition operation. The values are passed to the add function through x and y by calling it in main function. Those values are being recieved through formal parameters in function definition.

This is call by value. In this process, values of actual parameters will be copied to the formal parameters and these two parameters are stored in different locations. In call by value, one cannot modify the values of actual parameters by formal parameters.


What is call by reference?

In Call by reference memory address is passed to the callee function.

Both actual and formal parameters points to the same memory location. Therefore any changes made to the formal parameters will get reflected in actual parameters.

In this method, we pass addresses instead of values.

C program to illustrate call by reference

// C program to illustrate call by reference
#include<stdio.h>
int funct(int *pointer1, int *pointer2)
{
  *pointer1=30;
  *pointer2=10;
}
int main()
{
  int a=10,b=30;
  funct(&a,&b);
  printf("a=%d,b=%d \n");
  return 0;
}

Output

Call by reference example

Code explanation

In the program, We are passing addresses of variables a and b. We receive these addresses in special variables called pointers. These pointers point to the memory locations of variables.


People also ask for

Which one is better call by value or call by reference?

Call by reference uses pointer. Therefore if data values changes is expected, then only use call by reference otherwise use call by value.