Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference functions in C++

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?

like image 695
john smith Avatar asked Jun 09 '11 11:06

john smith


1 Answers

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.

like image 184
Sven Avatar answered Sep 28 '22 06:09

Sven