Ryan McGuire wrote:My point is that in cases where it does make a difference, ++i is more likely to one that's needed. If that's true, then I'd rather have had ++i become the standard rather than the exception.
In that code, I want i, j and k to all have the same value at the top of the loop. If I had used k = j = i++, the second time through the loop, i would be 1 while j and k are still 0.
Thanks, Ryan, for trying to examine this line of reasoning with me without getting defensive. I'm glad you took it the way I had hoped you would.
I fully agree with you about the (out loud) readability aspect of ++i that you described earlier. However—and I know you're just trying to make a point—this latest example you gave still fails to convince me that there's any compelling reason besides correctness of program logic to prefer to use ++i instead of i++.
The problem is related to what Campbell pointed out earlier: the examples we're giving are hardly "preferable" because they are examples of very poorly factored code. We can't ignore that and focus solely on the merit of ++i over i++. The context is always important and if the context we use stretches the bounds of reason, then our "proof" or reasoning is also shaky.
It's kind of like asking whether you'd prefer to die by heart attack or by drowning. Well, if you really think about it, any sane person would rather NOT die, right? So neither of the choices given is really a "preference". And saying "Well, if you HAD to make a choice" doesn't cut it either. We always have a choice to NOT write poorly factored code.
In your last example, the variables j and k presumably only start with the value of i in each iteration of the loop then subsequently change independently of i
in the for-loop body. Well, in that case, the variables j and k should not be included in the for-loop header since the only variable that factors into the loop control is the variable i
With this refactoring, it's clear that only the variable i
controls the loop iteration and now you're back to choosing between ++i or i++ as a matter of style and personal preference, not program correctness.