[FAQ] What is call-by-value and call-by-reference? (AKA pass-by-value and pass-by-reference)
Okay, this seems to cause a lot of confusion even amongst the experienced programmers.
This refers to the way an argument, the entity used when calling a function, is passed to the parameter, the local variable of a function.
call-by-value
This is where arguments are evaluated before the function is entered. The value of the arguments is use to instantiate (create/initialise) the parameter of the function. Changes to the parameter within the called function have no effect on the actual variable use as an argument to call the function.
call-by-reference
This is an argument passing convention where the address of an argument variable is passed to a function, as opposed to passing the value of the argument expression. Changes to the parameter within the called function change the actual variable use as an argument to call the function.
So let’s have a look at an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
// Here a, b and c are parameters of the function.
void Func(int a, int * b, int & c)
{
}
int main ()
{
int x = 0;
int * y = &x;
int z = 0;
// Here x, y and z are the arguments to
// the function call
Func(x, y, z);
return 0;
}
|
Parameter a
This is
call-by-value. When you call the function the value of the argument, x in this case, is used to instantiate the parameter a. Any change to the value of a inside the function will not be made to x.
Parameter b
This is the one that gives most people trouble. It is, again,
call-by-value. The argument y is evaluated and this value is used to instantiate the parameter b. If you change the value of the parameter b, i.e. make it point to another address, the value of the argument y is not changed.
As parameter b is a pointer that points to the same variable as the argument y does, it can be dereferenced to change that variable.
Parameter c
This is
call-by-reference. The address of the argument z is used to make a reference, the parameter c, so that c effectively becomes another name for z within the function. Any changes to c will directly change z.