Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference-type return functions and postfix increment

I am reading the Wikipedia page about references.

It contains the following code:

int& preinc(int& x) 
{ 
    return ++x;  // "return x++;" would have been wrong
}

preinc(y) = 5; // same as ++y, y = 5

I did try to compile using return x++; instead of return ++x;. As predicted, this led to the following error:

error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int’

I don't understand this error. I have the vague intuition that the incrementation of x happens too late (i.e., after the function call of preinc is over). However, I don't see how this is a problem since the variable x never ceases to exist. Any explanation is welcome.

like image 761
usual me Avatar asked Dec 04 '25 03:12

usual me


1 Answers

The cause of the error is that post increment x++ returns a temporary value, and this cannot be bound to a non-const lvalue reference. This is a simplified version of the same problem:

int i = 42;
int& j = i++; // Error: i++ returns temporary value, then increments i.
const int& k = i++; // OK, const reference can bind to temporary.
like image 174
juanchopanza Avatar answered Dec 06 '25 17:12

juanchopanza