Search code examples
c++referencepremature-optimization

Premature optimization or am I crazy?


I recently saw a piece of code at comp.lang.c++ moderated returning a reference of a static integer from a function. The code was something like this

int& f()
{
   static int x;
   x++;
   return x;
}

int main()
{
  f()+=1; //A
  f()=f()+1; //B
  std::cout<<f();

}

When I debugged the application using my cool Visual Studio debugger I saw just one call to statement A and guess what I was shocked. I always thought i+=1 was equal to i=i+1 so f()+=1 would be equal to f()=f()+1 and I would be seeing two calls to f(), but I saw only one. What the heck is this? Am I crazy or is my debugger gone crazy or is this a result of premature optimization?


Solution

  • This is what The Standard says about += and friends:

    5.17-7: The behavior of an expression of the form E1 op= E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once.[...]

    So the compiler is right on that.