Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 561
Prasoon Saurav Avatar asked Aug 09 '10 13:08

Prasoon Saurav


4 Answers

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.

like image 165
Nordic Mainframe Avatar answered Sep 22 '22 15:09

Nordic Mainframe


i+=1 is functionally the same as i=i+1. It's actually implemented differently (basically, it's designed to take advantage of CPU level optimization).

But essencially the left side is evaluated only once. It yields a non-const l-value, which is all it needs to read the value, add one and write it back.

This is more obvious when you create an overloaded operator for a custom type. operator+= modifies the this instance. operator+ returns a new instance. It is generally recommended (in C++) to write the oop+= first, and then write op+ in terms of it.

(Note this is applies only to C++; in C#, op+= is exactly as you assumed: just a short hand for op+, and you cannot create your own op+=. It is automatically created for you out of the Op+)

like image 21
James Curran Avatar answered Sep 23 '22 15:09

James Curran


Your thinking is logical but not correct.

i += 1;
// This is logically equivalent to:
i = i + 1;

But logically equivalent and identical are not the same.
The code should be looked at as looking like this:

int& x = f();
x += x;
// Now you can use logical equivalence.
int& x= f();
x = x + 1;

The compiler will not make two function calls unless you explicitly put two function calls into the code. If you have side effects in your functions (like you do) and the compiler started adding extra hard to see implicit calls it would be very hard to actually understand the flow of the code and thus make maintenance very hard.

like image 31
Martin York Avatar answered Sep 21 '22 15:09

Martin York


f() returns a reference to the static integer. Then += 1 adds one to this memory location – there's no need to call it twice in statement A.

like image 26
BjoernD Avatar answered Sep 25 '22 15:09

BjoernD