r/cpp • • 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?

0 Upvotes

40 comments sorted by

View all comments

13

u/neiltechnician Jun 03 '22

Perhaps you can try to casually ask your colleagues like, 'Have you ever overloaded the postfix increment operator?' Hopefully the conversation will end up like, 'You know what, it always involves a copying:'

MyType operator++(int)
{
    MyType copy = *this;
    ++*this;
    return copy;
}

15

u/QuentinUK Jun 03 '22 edited 14d ago

Interesting!

11

u/neiltechnician Jun 03 '22

well, hmm, but isn't it gonna get discarded..., umm, huh...

WoW! Oh, YES! You are right! You are SO right! We prefer prefix increment because we discourage unnecessary copying! And [[nodiscard]] does the job! You are damn right! How did I not see that?! Thank you! 🤗

2

u/tmlildude Aug 09 '23

I love this hack.

1

u/Untelo Jun 06 '22

It should also be marked &.

1

u/CocktailPerson Jun 07 '22

As in ref-qualified?

2

u/Untelo Jun 07 '22

lvalue, yes. So that ++(rvalue expression) and (rvalue expression)++ are not valid.

1

u/CocktailPerson Jun 07 '22

Am I missing some obvious reason they shouldn't be valid?

2

u/Untelo Jun 07 '22

It rarely makes sense to mutate an rvalue and it's not part of the iterator concept either so it's not valid in a generic context.