0

I fail to understand why the following program wrong:

 int& getID(){
   static int r = 0;
   return r++;
 }

main:

 int main(){
   int a = getID();
   std::cout << "a=" << a << std::endl;
   return 0;
 }

Why returning a static variable as described creates problems and not returning the wanted value?

7
  • no it wont print anything. my guess its because of the ++, but i cant understand why, its supposed to return a reference to r but non is given Commented Feb 11, 2012 at 15:53
  • Could you, please, post complete programs in the future? - sscce.org Commented Feb 11, 2012 at 15:55
  • 2
    This shouldn't compile: error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int’ Commented Feb 11, 2012 at 15:56
  • 3
    It should not compile. r++ returns int, not int &. Try r++; return r; instead. Commented Feb 11, 2012 at 15:56
  • 1
    r++ doesn't "return" anything. It evaluates to a prvalue. Commented Feb 11, 2012 at 16:00

5 Answers 5

7

You are using post-increment(r++ as opposed to ++r). The result of post-increment is a temporary, and you are trying to return a reference to that temporary. You can't do that. If you want to return a reference to r, then you can use pre-increment, or you can just do the increment, then in a separate statement, return r.

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

Comments

1

It doesn't return a reference to r but a reference to r's value before it was incremented. And that is probably lost in action.

Try

r++;
return r;

or

return ++r;

Comments

1

What you're running into is undefined behavior. Anything can happen.

r++ returns a temporary, and it's UB returning temporaries by reference.

On my platform, for example, it doesn't even compile.

Comments

1

Make your function return int not int & and all will be well. You want to return the value of the new id, not a reference to the function's internals.

Comments

0

You should read about prefix and postfix operator and how they are implemented.

Basically, ++i does this (prefix):

i += 1;
return i;

And i++ does (postfix):

ans = i;
i += 1;
return ans;

According to mentioned page, only the prefix operator++ returns reference to upgraded variable. Postfix (i++) returns new variable.

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.