Saturday, January 31, 2009

Prefix and Postfix operators in C++?

Thanks to stackoverflow "JProgrammer"

"Taking a leaf from Scott Meyers, More Effective c++ Item 6: Distinguish between prefix and postfix forms of increment and decrement operations.

The prefix version is always preferred over the postfix in regards to objects, especially in regards to iterators.

The reason for this if you look at the call pattern of the operators.

// Prefix
Integer& Integer::operator++()
*this += 1;
return *this;

// Postfix
const Integer Integer::operator++(int)
Integer oldValue = *this;
return oldValue;

Looking at this example it is easy to see how the prefix operator will always be more efficient than the postfix. Because of the need for a temporary object in the use of the postfix.

This is why when you see examples using iterators they always use the prefix version.

But as you point out for int's there is effectively no difference because of compiler optimisation that can take place.

No comments: