0
Pass by reference VS pass by pointer
Whats the difference between two in C++?
3 Respuestas
+ 9
A reference variable is an alias of an existing variable.
int a = 39;
int& b = a;
// both a and b refer to the same variable.
A pointer is a variable which stores the address of another variable,
int a = 39;
int* b = &a;
While both pass-by-reference and pass-by-pointer may be done due the same purpose, i.e. to change the value of the variable passed as a parameter to the function, within the function body, there are some subtle differences, such as the need to dereference a pointer in the function body.
void change1(int* a) {
*a = 39; // dereference the pointer before altering the value
}
void change2(int& a) {
a = 39; // alter the reference variable
}
int main() {
int a1 = 38, a2 = 38;
change1(&a1); // pass address of a1
change2(a2); // pass a2 directly
}
+ 1
A practical recommendation I have read:
When you want to change the value you pass, use a pointer; when you just want to read the data, use a reference but make it const.
The point was to keep your code maintainable.
A call by value looks exactly like a call by reference:
f(x)
So by just calling the function you can't tell if it has the power to mess around with the original variable or not.
A call by pointer looks differently:
f(&x)
So here you explicitly and knowingly you grant the function the right to modify x.