Thursday, July 9, 2009

Difference between call by value and call by reference in C?

Other answers look good, I thought I would add with some C code to further illustrate. In the below examples, the "changeit" function changes the value of the variable passed to it. Note that in pass by reference, we add the "*" indirection operator that says the changeit function does not accept an integer, but a pointer to an integer. And when we call the function, we do not pass i, but we pass %26amp;i, the address of i. The end result is that when we PASS BY VALUE the variable in the calling function is NOT changed, because it was passed by value (that is, it was copied) to the function, and when the function says i=99 it is ONLY changing its own local copy, while the i back in main() stays untouched. In CALL BY REFERENCE we are not making a copy, but actually passing a pointer, the actual memory address where the variable lives, so now if the function changes it, we are changing the actual variable. Look at these two example programs below. The first one will print out i=1 and i=1, while the second one will print i=1 and i=99.





// CALL BY VALUE


#include %26lt;stdio.h%26gt;


void changeit(int);


void main()


{


int i=1;


printf("i = %d\n",i);


changeit(i);


printf("i = %d\n",i);


}





void changeit(int i)


{


i=99;


}





// CALL BY REFERENCE


#include %26lt;stdio.h%26gt;


void changeit(int *);


void main()


{


int i=1;


printf("i = %d\n",i);


changeit(%26amp;i);


printf("i = %d\n",i);


}





void changeit(int *i)


{


*i=99;


}

Difference between call by value and call by reference in C?
CALL BY VALUE= In call by value, a copy of the variable is made and passed to the function as argument.By doing this changes made to the parameter of the function have no effects on the variable in the calling function, because the changes are made only to the copys.





CALL BY REFERENCE= Is a method in which the address of each argument is passed to the function, by doing this the changes made to the parameter of the function will affect the variable in the calling function.
Reply:in call by value if ur swapping values then they will not be swapped because the actual value of the identifier will be considered


in call by reference if ur swapping values then they will be swapped because the address of the identifier will be considered.


No comments:

Post a Comment