Call by Reference

Calling a function by reference


Calling by reference is different from calling by value, while calling by value passes  the copy of the original value and not the value itself (as an argument) and thus no changes are made to the original value, in calling by reference the address of the original value (reference) is passed on which means the original value is also accessible now.

when calling a function, instead of passing the actual variables, their address can also be passed.By doing so, the address of those variables will be copied into parameter variables and parameter variable will only point to the actual argument variables in memory.

call by reference

This type of function call is called call by reference. In such a function call, the address of actual arguments variables is passed. By doing so, changes in the values of parameter variables within the function, changes in values of actual argument variables occur.  that is, changes in the parameters also change the arguments.

In this type of function call, the arguments are passed along with the address of operator(&). it passes the address of operator argument to parameter variables. Apart from this, the parameters in the declaration and definition of the function are defined with the value at (*) operator.

  • In the Call by Reference, the address of the variable is passed to the function as a parameter.
  • In Call by Value, the actual parameter value is not copied on the formal parameter. 
  • In this , Actual Arguments only reach function from main as formal arguments.
Call By Reference

To fully understand the difference check the code for calling by value by clicking here, and then the code below

void fun(int *num)
printf("Value of a before adding in function %d\n",*num);
printf("Value of a after adding in function %d\n",*num);
int main()
int a=10;
printf("Value of a before passing it to function %d\n",a);
fun(&a); //passing value of a to function by reference
printf("Value of a after passing it to function %d\n",a);

Output :

Value of a before passing it to function 10
Value of a before adding in function 10
Value of a after adding in function 20
Value of a after passing it to function 20

Notice how we were able to change the original value and modify it outside the main function.This is not possible in call by value.

Here’s the another example:

Here the variable’a’ and ‘b’ address in the program are passed to the function ‘add’.

Here the values ‘a’ and ‘b’ are not copied to ‘x’ and ‘y’ variable.

it just holds the address of the variables.

void swap(int*x, int*y);
int main()
           int a=4, b=5;
           printf("before swapping a=%d and b=%d",a,b);
swap(&a, &b);
void swap(int *x, int*y)
int temp;
         temp = *x;
        *x = *y;
         *y = temp;
         printf("After swapping a =%d and b=%d", *x, *y);