← Back to context

Comment by card_zero

16 hours ago

People seem to mostly write a typical for loop ending with ; ++i){

But I write ; i++){ and seeing it the other way round throws me off for a minute, because I think, as you put it, why would you use those very particular semantics?

But I guess this is only a semantic argument.

In C++ the semantics can differ, in that copying an object for post-increment might require a memory allocation internally (for example in the case of a BigInt class), which may fail and throw an exception. For consistency, using pre-increment by default and unless you really need post-increment, is a good habit.

> why would you use those very particular semantics?

The difference is that i++ has to keep a copy to the original around as the return value is the pre-increment value, while with ++i that isn't needed as the resulting value is being returned.

In the for loop that shouldn't matter as a) for an integer it is essentially for free (it is just reordering when the relevant register is set) and b) that value is hopefully optimized out anyways by the compiler, however as there are cases where it matters some people prefer the ++i style, some just think it looks better.

It makes no difference if the increment is done on an int, but it can make a different if your `i` is some object with its own ++ operator.

I've seen either style, but it the argument about which is proper is pointless. Any modern compiler will optimize either equally well, unless you're doing something that actually depends on the order of the increment.

  • No, for fundamental datatypes pre/post-increment doesn't matter, but for classes that overload those operators, the postfix form creates a temporary object hence people write

    for(auto it = begin(v); it != end(v); ++it)