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.