Prefix Versus Postfix Operators

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 efficientDate temp(*this); //create a copy of the current objectthis.AddDays(1); //increment  current objectreturn temp; //return by value a copy of the object before it was incremented}Date& operator++() {  // ++Date is more efficientthis.AddDays(1); //increment  current objectreturn *this; //return by reference the current object}		   };
See also  How College Students Can Shape the Future of Tech Responsibility

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist