Home > OS >  c function call - pass by reference calls pointer method / pass by value calls referense method
c function call - pass by reference calls pointer method / pass by value calls referense method

Time:01-26

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

CodePudding user response:

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

  •  Tags:  
  • Related