0

I have see code that pre-increment (or decrement) of variables without return value to be used.

++i;  

vs

i++;

Example here : https://referencesource.microsoft.com/#mscorlib/system/threading/SemaphoreSlim.cs,809

Is there any purpose of doing this (expect coding style) ? Does it result in different assembler code to be generated by the VM ?

tigrou
  • 4,236
  • 5
  • 33
  • 59
  • 1
    Don't know about C#, but in C++ with optimizations switched on this will produce the same machine code. But it makes difference while reading the source, the `++i` is "increment i and result into that". The `i++` is "increment i, and result into the old value". People who use postfix-form without actually needing the original value are sort of not knowing what they are doing (if you take it to the extreme), because to "just increment" the prefix form is more accurate. So it's purely style/opinion thing as long, as resulting value is unused. – Ped7g Oct 12 '17 at 21:46
  • Or `i += 1;`. It makes a difference when it used in an expression. But this is a statement and the expression value is not used. So it doesn't matter, the exact same machine code is generated, and it is down to a style preference. If the variable name is long then I suspect people find the pre-increment version easier to read. – Hans Passant Oct 12 '17 at 22:37
  • Have you checked if it results in different assembly? – fuz Oct 12 '17 at 22:46
  • 2
    @Ped7g: In C++, it can matter if `i` is a class type with complicated pre and post-increment operator overloads. Post-increment has to return the old value, so the way it's written can result in a copy that doesn't optimize away (especially if it's not trivially copyable, or calls some non-inline functions). (Often post-increment is implemented as `T tmp = *this; ++*this; return tmp;`.) This is why `++i` is recommended any time you could choose either without doing extra work. – Peter Cordes Oct 12 '17 at 23:40
  • @PeterCordes sure, I felt for the trap, seeing "i" which I use only as integer-kind short lived temporary variables and nothing else, I don't expect class instance under such cryptic variable name. Also `std::atomic` would want a word with my simplification for sure... ;) Then again the example link leads to `int` type, so that's probably context of the question. – Ped7g Oct 13 '17 at 00:13

0 Answers0