Difference Between Call by Value and Call by Reference in C Programming

There are two methods available to pass arguments or parameters, i.e.

  • Call by Value
  • Call by Reference

The main difference between these two is, in the call by value a copy of actual arguments is passed to the respective formal arguments. Which means this will not affect the original value of the variable in the calling function. While, in the call by reference, the location of actual arguments is passed to formal arguments, i.e. any change made in formal arguments will also reflect in actual arguments.

Let’s take examples of both the types in C language:

Example: Call by Value

#include<stdio.h>

int main() {

    int num1=10,num2=20;
    interchange(num1,num2);

    printf("\nNumber 1 : %d",num1);
    printf("\nNumber 2 : %d",num2);

    return(0);
}

void interchange(int number1,int number2)
{
    int temp;
    temp = number1;
    number1 = number2;
    number2 = temp;
}
Output:
Number 1 : 10
Number 2 : 20

In the above example, the copied version of num1 and num2 is passed inside the number1 and number2 of the interchange function.

Example: Call by Reference

#include<stdio.h>

int main() {

    int num1=10,num2=20;
    interchange(&num1,&num2);

    printf("\nNumber 1 : %d",num1);
    printf("\nNumber 2 : %d",num2);

    return(0);
}

void interchange(int *num1, int *num2)
{
    int temp;
    temp  = *num1;
    *num1 = *num2;
    *num2 = temp;
}
Output:
Number 1 : 20
Number 2 : 10

In this above example, we are passing the address of the variable to the called function. Any changes made inside the function will also modify the original values.
To sum up, here’s a short difference table to make it more clear:

[table id=1 /]

[print-me/]

Add a Comment