Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning reference to a variable in C++

Tags:

c++

reference

My question is why it is possible to assign reference to a variable that is not declared as reference?

Thank you.

int &testRef(int &x)
{
    return ++x;
}

int main()
{
    int x = 1, y;
    y = testRef(x); // assigning testRef(x) which is int& to y which is int
    return 0;
}
like image 653
Diesel DL Avatar asked Dec 09 '22 05:12

Diesel DL


1 Answers

y = testRef(x); will take a value copy of the reference returned by testRef. That can be useful if you want to make subsequent modifications to the return value.

If testRef were to return a const reference, then you'd have no choice but to take a value copy if you wanted to change the return value. That helps in achieving program stability.

like image 176
Bathsheba Avatar answered Dec 10 '22 19:12

Bathsheba