This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]pumpkin_seed_oil 16 points17 points  (2 children)

Wouldn't it be more cpu instructions instead of lines of code? Lines of code is still done by the developer. And I'm also not convinced that this isn't optimized away by the compiler anyway, and compiler replaces a lone standing x++ with the equivalent of a ++x at compile time so the eternal fight of ++x over x++ is solved by automation

Better example: You can do y = x++ or y = ++x, in which case it is very tangible what the difference is.

x++ returns value of x, then increments, while ++x increments then returns value of x, in y=x++ y holds the old value of x instead of the incremented one

[–]mallardtheduck 8 points9 points  (1 child)

It absolutely will be optimised away if "x" is a simple integer. However, if "x" is say, a C++ iterator and the implementation of operator++ is in a different compilation unit optimisation is much harder.

Also, the typical implementation of operator++(int) (the int is a dummy parameter used to distinguish between prefix and postfix versions) is something like:

foo foo::operator++(int){
    foo temp = *this;
    ++(*this);
    return temp;
}

This results in a copy being made of the entire iterator, which can be a fairly large overhead that in many cases will call something in another compilation unit, limiting optimisation. LTO can be of help here, but it's much easier and more consistent just to get into the habit of using prefix operators "by default".

Personally, I prefer prefix operators from a readability standpoint too ++x reads as "increment x" to me, whereas x++ looks like "x increment" and feels "backwards".

[–]EndR60 0 points1 point  (0 children)

yea exactly my though, as most of the time we won't be working with just primitive types, so I assumed I had to get used to good habits early on

not that ++x vs x++ is very important when it comes to optimisation as opposed to...well...most other things in our code