-2

A function call is made in the code. In the first function call a pass by reference is performed calling the pointer function. In the second function call a pass by value is performed where the reference function is called.

Why is this so?

#include <iostream>
void f(int *p) { (*p)++; }
void f(int &p) { p-=10; }
int main() {
 int x=0; f(&x); f(x); f(&x);
 std::cout << x << "\n";
}
forty4seven
  • 73
  • 1
  • 4
  • 3
    `f(&x)` is not passing by reference, it is using the address-of operator to get the objects address. Sounds like you could use a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver Jan 25 '22 at 20:51

1 Answers1

2

x is an int variable. &x is taking the address of x, yielding an int* pointer.

f(&x) can't pass an int* pointer to an int& reference, but it can pass to an int* pointer, so it calls:

void f(int*)

f(x) can't pass an int variable to an int* pointer, but it can pass to an int& reference, so it calls:

void f(int&)

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770