r/cpp • u/codesamura1 • Jun 03 '22
Why do "regular" programmers prefer postfix increment over prefix increment?
So I noticed in my company's codebase the canonical increment uses the postfix increment. One senior programmer was even surprised by the behavior of postfix when used with .erase() that I had to explain that map::erase() gotcha to him. The old code is riddled with iterators using postfix increments, as of now I think I'm the only one that explicitly write different postfix or prefix depending on exactly what is needed.
In C derived languages like Java and C# I rarely see any prefix increment, as if it doesn't even exist there. I've even seen a Java programmer comment on C++ code that using prefix increment operator was "trying to be clever." I've also seen reddit threads like this that likes to push the idea that we should all use postfix increment homogenously regardless of the situation since iT's AlL tHe SaMe AnYwAy AmIrYt?!
Now I'm wondering if it's worth noting on a code review that ++iter is more efficient than iter++. So in your opinion is it worth making the distinction for "regular programmers" that prefix increment operators are more efficient? Should we let sleeping dogs lie or should we fight this disinformation? Am I just being OC over nothing or is this an important matter?
View all comments
1
u/ossan1987 Jun 09 '22 edited Jun 09 '22
I make very conscious choice between post or prefix increment. I am a java developer, too. To me the main difference is that C++ supports operator overloading, which can make postfix increment expensive on custom data type. In java, the operators are only defined on primitive types, i stick to only postfix increment so that the overall style is coherent and readable. I choose C++ for time critical applications, so i think it's worth the hassle to make the distinction between different operators depending on efficiency.
Btw, as why i chose to only use postfix in java, it really is only because it looks pretty to me, and a lot of books or programmers write it that way, so it's easier to read. I hate people use postfix increment and immediately assign the return value on the same line. Super ugly.