References in c++

int& preinc(int& x) {
return ++x; // "return x++;" would have been wrong
}
preinc(y) = 5; // same as ++y, y = 5


Why ++y=5 don't give any error and y++=5 gives error???
Because the postfix increment operator results in a temporary.
It returns a temporary int with the previous value and increases the value of the original variable. A temporary can't be used as an lvalue, so an assignment won't work.
The prefix increment operator increases the original variable and returns a reference to it. Therefore there is no problem in this case.
Topic archived. No new replies allowed.