In programming on the basis of passing parameters to a function we classified function invocation into two : Call by value and Call by reference.As name suggest in both invocations we are calling function by type of parameters in one we are passing actual value of parameter and in other we are passing the location/reference of parameter.
Following are the important differences between Call by Value and Call by Reference.
Sr. No. | Key | Call by Value | Call by Reference |
---|---|---|---|
1 | Naming Convention | As in this type the value of parameter is get passed for function invocation hence it is named as Call by Value. | On other hand in this type the reference of parameter is get passed for invoking the function so it is named as Call by Reference. |
2 | Internal implementation | In Call by value the value of parameter we passed during calling of function are get copied to the actual local argument of the function. | In Call by reference the location address/reference of passed parameter is get copied and assigned to the local argument of the function so both passed parameter and actual argument refers to the same location. |
3 | Effects of changes | As value of passed parameter is copied to argument of function so any change done in argument inside the function do not get reflected in the passed parameter. | As both argument and passed parameter refers to the same location hence any change done to argument inside the function get reflected in the passed parameter. |
4 | Referred Memory location | Memory location referred both passed parameter and actual arguments of function is different. | Memory location referred by both passed parameter and actual argument of function is same. |
5 | Supported languages. | Call by value is get supported by languages such as : C++.PHP. Visual Basic NET, and C#. | Call by reference is primarily get supported by JAVA. |
Example of Call by value vs Call by reference
ByValue.c
#include <stdio.h> class ByValue{ void swapByValue(int, int); /* Prototype */ int main(){ int n1 = 10, n2 = 20; swapByValue(n1, n2); printf("n1: %d, n2: %d\n", n1, n2); } void swapByValue(int a, int b){ int t; t = a; a = b; b = t; } }
Output
n1: 10, n2: 20
Example
ByReference.c
#include <stdio.h> class ByReference{ void swapByReference(int*, int*); int main(){ int n1 = 10, n2 = 20; swapByReference(&n1, &n2); printf("n1: %d, n2: %d\n", n1, n2); } void swapByReference(int *a, int *b){ int t; t = *a; *a = *b; *b = t; } }
Output
n1: 20, n2: 10