Reputation: 16764
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?
Upvotes: 0
Views: 4785
Reputation: 18964
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.
Upvotes: 1
Reputation: 20997
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.
Upvotes: 0
Reputation: 258568
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.
Upvotes: 1
Reputation: 103693
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.
Upvotes: 7
Reputation: 92231
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;
Upvotes: 1