By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,133 Members | 1,319 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,133 IT Pros & Developers. It's quick & easy.

prefix vs. postfix

P: n/a
Hi,

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

Thanks
Chris
Jul 23 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Christian Christmann wrote:
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.
Jul 23 '05 #2

P: n/a
Christian Christmann wrote:
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.

Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.