Frage

I heard a professor saying "Avoid postfix operator where the context allows to choose prefix". I search but I didn't found related posts in stackoverflow that explaining this.

Why to prefer prefix operator++ to postfix operator++ when we have the ability to choose either one?

War es hilfreich?

Lösung

The prefix operator++ does a single operation -- increment the value.

The postfix operator++ does three operations -- save the current value, increment the value, return the old value.

The prefix version is conceptually simpler, and is always (up to bizarre operator overloads) at least as efficient as the postfix version.

Andere Tipps

I'm pretty sure your professor is talking about the old speed difference between the prefix and postfix ++ operator. I'm also pretty sure it no longer matters which you choose as modern compilers usually are smart enough to recognize if it can be optimized out.

Also, depending on your code you might be required to use one or the other for correctness.

The prefix operator is potentially faster than the postfix operator, depending on the type on which it's operating. It should never be slower.

For most intrinsic types, the speed should be identical. However, many custom iterators need to make an extra copy of some state object in order to properly implement the postfix operator.

In order to implement the postfix operator, a copy of the original object has to be taken because that's what gets returned back to you.

For the prefix operator, you get the new object back, saving the copy overhead.

Some folk (rightly) will tell you that the compiler will optimise out unintentional postfix copies; for example in code like for (int n = 0; n < large; n++)

I'd always prefer to see ++n.

Infact, I'd rather the language be called ++C; not C++!

There's no real reason, except for stylistic issues. One noted specialist recommended it once, and everyone blindly followed, although the measures I did indicated that it made no difference.

If you're starting on a green fields project, I'll use prefix, but the motivation is just to avoid stupid discussions about the issue. If I'm working on existing code, I'll continue to use whatever was most common, because in real code, it makes absolutely no difference, despite claims to the contrary.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top