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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With