Call by value and call by reference in c


Call By Value

  • In call by value, original value is not modified.In call by value, value being passed to the function is locally stored by the function parameter in stack memory location.
  • If you change the value of function parameter, it is changed for the current function only.
  • It will not change the value of variable inside the caller method such as main().

    Example:

    #include <stdio.h>
    void swapnum( int var1, int var2 )
    {
       int tempnum ;
       /*Copying var1 value into temporary variable */
       tempnum = var1 ;
    
       /* Copying var2 value into var1*/
       var1 = var2 ;
    
       /*Copying temporary variable value into var2 */
       var2 = tempnum ;
    
    }
    int main( )
    {
        int num1 = 35, num2 = 45 ;
        printf("Before swapping: %d, %d", num1, num2);
    
        /*calling swap function*/
        swapnum(num1, num2);
        printf("\nAfter swapping: %d, %d", num1, num2);
    }
    
    

    Output:

    Before swapping: 35, 45
    After swapping: 35, 45

Call by reference

  • In call by reference, original value is modified because we pass reference (address).
  • Here, address of the value is passed in the function, so actual and formal arguments shares the same address space.
  • Hence, value changed inside the function, is reflected inside as well as outside the function.

    Example:

    #include <stdio.h>
    void swapnum ( int *var1, int *var2 )
    {
       int tempnum ;
       tempnum = *var1 ;
       *var1 = *var2 ;
       *var2 = tempnum ;
    }
    int main( )
    {
       int num1 = 35, num2 = 45 ;
       printf("Before swapping:");
       printf("\nnum1 value is %d", num1);
       printf("\nnum2 value is %d", num2);
    
       /*calling swap function*/
       swapnum( &num1, &num2 );
    
       printf("\nAfter swapping:");
       printf("\nnum1 value is %d", num1);
       printf("\nnum2 value is %d", num2);
       return 0;
    }
    
    

    Output:

    Before swapping:
    num1 value is 35
    num2 value is 45
    After swapping:
    num1 value is 45
    num2 value is 35