I have a function that gives me the error "cannot convert from 'int' to 'int &'" when I try to compile it.
int& preinc(int& x) {
return x++;
}
If I replace x++ with x, it will compile, but I'm not sure how that makes it any different. I thought that x++ returns x before it increments x, so shouldn't "return x++" be the same as "return x" with regard to what preinc returns? If the problem is with the ++ operator acting on x, then why won't it generate any error if I put the line "x++" before or after the return statement, or replace x++ with ++x?
x++
creates a temporary copy of the original, increments the original, and then returns the temporary.
Because your function returns a reference, you are trying to return a reference to the temporary copy, which is local to the function and therefore not valid.
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