Call by Value and Call by Reference in C

 

Call by Value

In C, In call by value, a copy of the argument is passed to the function. Any modifications made to the argument within the function do not affect the original value outside the function.

Example:

void swap_values(int x, int y) {
    int temp = x;
    x = y;
    y = temp;
}

int main() {
    int a = 10, b = 20;
    swap_values(a, b);
    printf("a = %d, b = %dn", a, b); // Output: a = 10, b = 20
    return 0;
}

In this example, swap_values is called by value, so the original values of a and b remain unchanged.

Call by Reference

In call by reference, the address of the argument is passed to the function. This allows the function to modify the original value.

Example:

void swap_references(int *x, int *y) {
    int temp = *x;
    *x = *y;
    *y = temp;
}

int main() {
    int a = 10, b = 20;
    swap_references(&a, &b);
    printf("a = %d, b = %dn", a, b); // Output: a = 20, b = 10
    return 0;
}

In this example, swap_references is called by reference, so the original values of a and b are swapped.

Key Differences: Call by Value vs Call by Reference

Difference Between Call By Value and Call By Reference

Feature Call by Value Call by Reference
Argument Passing Copy of the argument is passed. Address of the argument is passed.
Modifications Changes within the function do not affect the original value. Changes within the function affect the original value.
Efficiency Generally more efficient, as a copy is not created. Can be less efficient due to the overhead of passing addresses.

When to Use Which:

  • Use call by value for simple data types when you don’t need to modify the original value within the function.
  • Use call by reference when you need to modify the original value of a variable within a function. This is often used for passing large data structures or modifying global variables.

Call By Reference. While calling a function, we pass values of variables to it. Such functions are known as “Call By Values”. While calling a function, instead of passing the values of variables, we pass address of variables(location of variables) to the function known as “Call By References.

Related Posts

Leave a Reply