Close
Close

difference between calling pointers with call by value and call by reference

   Renuka


Answers

  •   

    While calling a function, passing the variable as function parameter is passing by value and passing the pointer to the variable as function parameter is passing by referance.

    Passing by value

    Let’s first look at an example to understand this.

    #include <stdio.h>
    
    void func(int a, int b)
    {
    	int t;
    	t = a;
    	a = b;
    	b = t; 
    	
    	printf("In the function :\n");
    	printf("a : %d\n", a);
    	printf("b : %d\n", b);
    }
    
    int main() {
    	int num1 = 5, num2 = 6;
    	func(num1, num2);
    	printf("num1 : %d\n", num1);
    	printf("num2 : %d", num2);
    	return 0;
    }
    

    Here we passed the numbers num1 and num2 to the function func. Since we passed the variables itself, the values of the function parameters a and b became equal to the respective values of the function arguments num1 and num2 i.e. 5 and 6 respectively. Thus, it is called passing by value. 

    In the function, the values of a and b (i.e. the copies of num1 and num2) got interchanged and not of num1 and num2. So, our output is

    In the function :
    a : 6
    b : 5

    num1 : 5
    num2 : 6

    Passing by referance

    In passing by referance, we pass the address (referance) of the variable to the function. Look at the example.

    #include <stdio.h>
    
    void func(int *a, int *b)
    {
    	int t;
    	t = *a;
    	*a = *b;
    	*b = t; 
    }
    
    int main() {
    	int num1 = 5, num2 = 6;
    	func(&num1, &num2);
    	printf("num1 : %d\n", num1);
    	printf("num2 : %d", num2);
    	return 0;
    }
    

    In this example, we passed the addresses of the variables num1 and num2 to the function Since this time we interchanged the values of the addresses of the original variables, so the values of the original variables also got interchanged (because unlike values, we cannot change the address of a variable). The output of the above program is as follows.

    num1 : 6
    num2 : 5



Ask Yours
Post Yours
Write your answer