News for hackers. Stuff that matters.
Re:The C23 edition of Modern C is now available for free by card_zero on Tuesday October 15, 2024 @02:25PM (#41851532)
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.

Re:The C23 edition of Modern C is now available for free by johannes1234321 on Tuesday October 15, 2024 @02:41PM (#41851721)
> 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.

Re:The C23 edition of Modern C is now available for free by layer8 on Tuesday October 15, 2024 @03:34PM (#41852277)
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.
Re:The C23 edition of Modern C is now available for free by secondcoming on Tuesday October 15, 2024 @04:08PM (#41852595)
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.
Re:The C23 edition of Modern C is now available for free by Quekid5 on Tuesday October 15, 2024 @03:52PM (#41852443)
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.
Re:The C23 edition of Modern C is now available for free by kanbankaren on Tuesday October 15, 2024 @04:14PM (#41852642)
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)