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?
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.