The operator of &a
means the address of variable a, the operator of *a
means the content of memory addressed by variable a. Now the function definition is following:
void callByRef(int &a, int &b){
a += 3;
b -= 2;
return;
}
where int &a
means that a will be a reference to some variable of type int. Therefore whenever you gong to call the function you need to pass the variable itself rather its address, hence callByRef(a, b)
and not callByRef(&a, &b)
.
The reason of such declaration is following, parameters passed to the function, passed by value, namely the content of the variable literally copied into function variable, therefore any change to it inside the function won't have any effect. For example:
void callByVal(int a, int b){
a += 3;
b -= 2;
return;
}
and having:
x = 5;
y = 10;
calling callByVal(x, y)
won't have any effect on x and y. To overcome this, you need to pass parameters either by reference or int &a
or as an alternative you can pass pointer and update memory directly:
void callByPtr(int *a, int *b){
*a += 3;
*b -= 2;
return;
}
And now it make sense to pass variables addresses, e.g. callByPtr(&a, &b)
.