What are the differences between these two function declarations?
In theory, all the rules about pass-by-value and pass-by-reference still apply, ie,:
- Pass-by-value: the original value in the caller does not change
- Pass-by-reference: the original value in the caller may change
Those things still apply here in the context of pointer. The only thing needs to remember is that the "original value" is of the pointer itself - not the object it points to.
void foo(int* p); // Call by value to pointer
Changes to p
itself does not affect the original p
from the caller.
So if you do ++p
inside foo
it would advance the pointer within the function while leaving the original pointer intact.
void func(int*& p); // Call by reference to pointer
Changes to p
inside func
would affect the original pointer from the caller.
So if you do *(++p) = 5;
inside func
it would advance the pointer. And assume it still points to something valid in the caller, that would make the value pointed to by p
in the caller to be equal to 5 as well.