0

I have this function:

void fun(int x, int& sum)
{
sum = x * x;
}

what is wrong with:

fun(4, &y);
fun(4,5);
Some programmer dude
  • 380,411
  • 33
  • 383
  • 585

2 Answers2

0

&y is not a reference. It is a pointer to variable y. If you want to pass it by reference you just pass it like so:

fun(4, y);
Yevhen Kuzmovych
  • 7,193
  • 5
  • 23
  • 40
0

In this function call

fun(4, &y);

argument y has type of pointer while the corresponding parameter is reference to int.

If y is defined like

int y;

then the valid function call will look like

fun(4, y);

This function call is invalid

fun(4,5);

because the second argument is a temporary expression that is not lvalue. Thus it may be bound to a constant reference. However the corresponding parameter is declared as a non-constant reference because the parameter is changed in the function. Thus the compiler will issue a diagnostic message.

Vlad from Moscow
  • 265,791
  • 20
  • 170
  • 303