5

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?

3
  • 2
    I'd call this "postinc" rather than "preinc".... Commented Jun 9, 2011 at 11:07
  • 1
    Thank you everyone who answered the question. I didn't realize x++ made a temporary copy. Makes sense now. Commented Jun 9, 2011 at 11:15
  • you are expected to accept one of the answers below. Commented Jun 28, 2011 at 11:50

3 Answers 3

11

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.

Sign up to request clarification or add additional context in comments.

Comments

11

Your function does two things:

  • Increments the x that you pass in by reference
  • Returns a reference to the local result of the expression x++

The reference to a local is invalid, and returning anything at all from this function seems completely redundant.

The following is fixed, but I still think there's a better approach:

int preinc(int& x) {
   return x++; // return by value
}

Comments

4

Yes, x++ returns x before it is incremented. Therefore it has to return a copy, the copy is a temporary and you can only pass temporaries as constant references.

++x on the other hand returns the original x (although incremented), therefore it will work with your function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.