← Back to context

Comment by jejdjdbd

16 hours ago

Why would you use post increment by default? The semantics are very particular.

Only on very rare occasions I need post increment semantics.

And in those cases I prefer to use a temporary to make the intent more clear

I rarely use pre-increment tbh, but post-increment all the time for array indices (since typically the array should be indexed with the value before the increment happens).

If the pre- or post-increment behaviour isn't actually needed, I prefer `x += 1` though.

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)

If you're used to the idiom, the intent couldn't be clearer.

I miss it when switching between C/++ and other languages.