You're online now.

Hurray! you are online now.

Call by Reference in C programming language

When we call a function and pass the variable / parameter in the function, when passing the address of the actual arguments from the calling function, that's why it is called call by reference.

In the call by reference inside the function, we use the address of the actual arguments, this means that when is a change in the parameter, it will be affected the passed argument.

// Example 1
    #include <stdio.h>
    
    void changeValue(int *a);
    
    int main() {
        
        int x = 40;
    // Before Calling the Function 
        printf("\nValue of x : %d", x);
        changeValue(&x);
        // After Calling the Function
        printf("\nValue of x : %d", x);
    
        return 0;
    }
    
    void changeValue(int *a){
        // Inside the function
        printf("\nInside the function Value of a Before perform some operation : %d", *a);
        *a = *a + 20;
        printf("\nInside the function value of a after perform operation : %d", *a);
    }
    
    /*
    
    Value of x : 40
    Inside the function Value of a Before perform some operation : 40
    Inside the function value of a after perform operation : 60
    Value of x : 60
    
    */
// Example 2
    #include <stdio.h>
    
    void swap(int *a, int *b);
    
    int main() {
        
        int x = 40, y = 60;
    // Before Calling the Function 
        printf("\nValue of x : %d and y : %d", x, y);
        swap(&x, &y);
        // After Calling the Function
        printf("\nValue of x : %d and y : %d", x, y);
    
        return 0;
    }
    
    void swap(int *a, int *b){
        // Inside the function
        printf("\nInside the function Value of a : %d and b : %d Before perform some operation", *a, *b);
        int temp = *a;
        *a = *b;
        *b = temp;
        printf("\nInside the function value of a : %d and  b : %d after perform operation", *a, *b);
    }
    
    /*
    
    Value of x : 40 and y : 60
    Inside the function Value of a : 40 and b : 60 Before perform some operation
    Inside the function value of a : 60 and  b : 40 after perform operation
    Value of x : 60 and y : 40
    
    */

Advantage of call by reference

  • Function can change the value of argument that's why it is very beneficial.
  • In call by reference function our memory space save which does not create the duplicate data for holding only one value.
  • In this method, no copy of the arguments is made, so it get processed very fast.

Disadvantage of call by reference

  • Function taking in a call by reference requires ensuring that the input is non-null. That's why null check is not supposed to be made. Thus is has a non-null guarantee.
  • Passing by reference makes the function not pure theoretically.
🖤 0
Buy me coffee ☕

Comments

Oops!

No comments here...