Call by reference is a method of evaluating arguments in a function (or method) call where a function receives an implicit reference to a variable used as argument, rather than a copy of its value
Function parameters(or formal parameters) are the names listed in the function definition
Function arguments(or actual parameters) are the real values passed to (and received by) the function when executed
In call by reference, the parameters of a function receive the references of the arguments passed to it when it is called
This typically means that the function can modify (i.e., assign to) the variable used as argument and the changes are visible to the caller (i.e. outside the function)
Consider following C code
void modify(int c, int* e) {
c = 27;
*e = 27;
}
int main() {
int a = 1;
int b = 1;
modify(a, &b); // a is passed by value, b is passed by reference by creating a pointer
return 0;
}
Typically, arguments are passed by value and objects are passed by reference
So if a function reassigns the value of a parameter(even if it is an object), the change is not visible to corresponding variable passed as argument
But if parameter is an object and the object is modified (without being re-assigned) then this change is visible to the caller
Consider following Java code
import java.util.*;
class CallByReferenceTest {
public static List<Integer> reassign(List<Integer> x) {
x = new ArrayList<Integer>();
x.add(12);
return x;
}
public static List<Integer> modify(List<Integer> x) {
x.add(12);
return x;
}
public static void main(String args[]) {
List<Integer> x = new ArrayList<Integer>();
List<Integer> y = new ArrayList<Integer>();
x.add(1); x.add(4);
y.add(2); y.add(6);
reassign(x);
modify(y);
System.out.println(String.format("x = %s", x));
System.out.println(String.format("y = %s", y));
}
}
Above program can be run as
What it shows is that, after list x is reassigned to a new list using reassign() function, it's value remains the same for the caller (main()
function)
But when a similar list, y is modified by adding data, its value gets updated for the caller