prefix vs. postfix

  • Thread starter Christian Christmann
  • Start date
C

Christian Christmann

Hi,

is there a difference in terms of efficiency
when using a prefix "++x;" instead of a
postfix "x++;"?

Thanks
Chris
 
R

Ron Natalie

Christian said:
Hi,

is there a difference in terms of efficiency
when using a prefix "++x;" instead of a
postfix "x++;"?

Depends what the type of x is and what the rest of the
expression is. With built in types, the difference is
negligable to non-existant as the compilers are pretty
good about optimizing either case. In the case of
user defined operator++ functions, it depends on the
definition of the function, but usually the x++ case
returns a copy of the object and ++x returns a reference
so the former is less efficient.
 
R

Rolf Magnus

Christian said:
Hi,

is there a difference in terms of efficiency
when using a prefix "++x;" instead of a
postfix "x++;"?

Depends on the type of x and possibly on the optimization capabilities of
the compiler. For built-in types, it's very likely that there is no
difference between prefix and postfix. If it's a user-defined type, then
postfix ++ needs to copy the object first, then increment the original,
then return the copy. So you get the overhead of a copy of the object. If
you don't need the old value, that copy is discarded, and so the code would
be less efficient (unless the compiler is able to optimize that away).
Prefix ++ OTOH just needs to increment the object and then return a
reference to it. No copy is needed.
That's why prefix ++ is preferred in C++ whenever there is no reason to use
postfix instead, and for the sake of consistency, many programmers do it
not only for user-defined types, but also for built-in types.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top