2

What are the differences between these two function declarations? I realized there is a difference between call by value and call by reference to a pointer.

void foo(int* p); // Call by value to pointer
void func(int*& p); // Call by reference to pointer

also is there any difference between r-value to l-value binding or something like that.

User8500049
  • 410
  • 3
  • 12
  • Does this answer your question? [Reference to a pointer](https://stackoverflow.com/questions/3128662/reference-to-a-pointer) or [What is a reference-to-pointer?](https://stackoverflow.com/questions/22374524/what-is-a-reference-to-pointer) – walnut Nov 24 '19 at 04:48
  • Also regarding reference binding: [Argument passing by reference to pointer problem](https://stackoverflow.com/questions/7308384/argument-passing-by-reference-to-pointer-problem) – walnut Nov 24 '19 at 04:54

1 Answers1

1

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.

artm
  • 17,291
  • 6
  • 38
  • 54