[SOLVED] c++ function call – pass by reference calls pointer method / pass by value calls referense method


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";


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&)

Answered By – Remy Lebeau

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *