Vasanth
Vasanth

Reputation: 21

Is it valid to return a reference as a reference valid in C++

#include <iostream>

using namespace std;

int& fun1(int& ref)
{
  ref = 30;
  return ref;
}

int main()
{
  int i = 10;

  i = fun1(i);
  cout << "Value of i:" << i << endl;

  return 0;
}

Output: Value of i:30

Is it valid to return a function argument passed as reference as a function return the same reference? According to my understanding ref in fun1(int& ref) will have a it's own memory location in the stack and returning the address of ref is invalid.

Upvotes: 0

Views: 71

Answers (2)

Fran&#231;ois Andrieux
Fran&#231;ois Andrieux

Reputation: 29072

References act in every way as if they were the original object. This means that taking the address of a reference gives the address of the original object and taking a reference to a reference gives a reference to the original object.

While there exists pointers to pointers, there is no such thing as a reference to a reference.

Take note the assignment in i = fun1(i); is redundant. i is already 30 in this case. You can simply call fun1(i);.

Upvotes: 2

John Zwinck
John Zwinck

Reputation: 249642

Yes, it's fine. What matters is that the lifetime of the referent is long enough.

Upvotes: 0

Related Questions