Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

The preincrement (++i) does the increment and then return a reference to the variable (Wich have been modified). Postincrement (i++) computes the result of the increment, stores it in a temp local variable, and return a copy of that result after it does the increment. This is done to make look that the increment is done after the call:

int operator++(int)
{
   int tmp( *this );
   ++(*this);
   return tmp;
}  

This code is for learning purposes, is not real code (int is not a class). Is for showing how postincrement works.

So, as you can see, i++ returns a copy, not a reference. So you cannot initialize the return value, because its a rvalue, not a reference to an existing variable.

you could try to increment x before returning it and see if it solves the problem

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

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top