4 ms·
C++ copies values differently (or at all) for different types under prefix increment vs. postfix increment? Seriously?
by silentOpen 17y ago
C++ copies values differently (or at all) for different types under prefix increment vs. postfix increment? Seriously?
- shrughes 17y agoYes. When overloading prefix and postfix increment, there are two functions to write, and the postfix version returns a copy of what you've incremented. It's impossible for a compiler to optimize this away in the general situation.
- dkarl 17y agoThere's no difference between C and C++, except that in C++, you can define prefix and postfix operators on user-defined types. The two are defined separately because C++ was created for people who are really finicky about performance. (For some reason some people are really bothered by the possibility that you could provide really insane definitions, as if it wasn't already possible to create insanely named functions and methods....) Anyway, even in C, ++i and i++ change the value of i and evaluate to a value. So there are two values: the new value of i, and the value of the expression. In the case of prefix ++, the two values are the same. In the case of postfix ++, the two values are different. If you ignore the value of the expression, then ++i and i++ can be used interchangeably. The compiler will probably figure this out and produce the same code.