4 ms·
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 case
by jejdjdbd 2y 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
- card_zero 2y agoPeople 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.
- johannes1234321 2y ago> 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.
- layer8 2y agoIn 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.
- Quekid5 2y agoI'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.
- kanbankaren 2y agoNo, 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)
- secondcoming 2y agoIt 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.
- codr7 2y agoIf you're used to the idiom, the intent couldn't be clearer. I miss it when switching between C/++ and other languages.
- flohofwoe 2y agoI 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.