Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Advanced
Aug 14, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Prefix Versus Postfix Operators

You can use both -- and ++ as prefix and postfix operators. When applied to primitives such as int or char, they are indistinguishable in terms of efficiency. When applied to objects, on the other hand, the overloaded prefix operators are significantly more efficient than the postfix ones. Therefore, whenever you're free to choose between postfix or prefix operators of an object, you should prefer the latter:
Void f() {
Date d1, d2;
d1++;  d2--  //inefficient: postfix operator
++d1;  --d2;  //prefix is more efficient
The reason is that the postfix version usually involves a construction of an extra copy of the object, in which its state is preserved, whereas the prefix version is applied directly to its object:
class Date
Date operator++(int unused) {  // Date++ is less efficient
Date temp(*this); //create a copy of the current object
this.AddDays(1); //increment  current object
return temp; //return by value a copy of the object before it was incremented
Date& operator++() {  // ++Date is more efficient
this.AddDays(1); //increment  current object
return *this; //return by reference the current object
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date