Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why to avoid postfix operator in C++? [duplicate]

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?

like image 243
Avraam Mavridis Avatar asked Aug 05 '26 17:08

Avraam Mavridis


1 Answers

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.

like image 86
Mankarse Avatar answered Aug 08 '26 10:08

Mankarse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!