Q: Someone told me that if I want to increment a variable and that's all, I should use ++x instead of x++. Is this true?
A: If incrementing is all that you want to do (you are not assigning the variable to something else), then yes this is a good practice, especially if you are using the increment operator on a class.
++x;
For the standard data types there is usually no performance difference, but for classes there are! The reason is that (for most common implementations of) postfix operators retain a temporary copy of original variable and because the return value is returned by value, not by reference. The following code exemplifies this:
MyClass operator++(int) //Postfix increment operator (x++)
{
MyClass temp = *this;
//Perform increment operation
return temp;
}
};
Q: So what form of increment/decrement operator should I use for fundamental types when I can use either. For example:
A: Use the pre-incement/decrement form (++i and --i)
Even though there is little impact for fundamental types, since we programmers are human, you will produce programming habits. And those habits will cary over to when we deal with classes instead, for example iterators.
There was an informal study done (sorry I forgot the source) on a number of people who say "I only use post-incrementing/decrementing for fundamental types." The results showed that they very frequently used the post-increment/decrementing operators for iterators and other classes leading to a great amount of wasted CPU cycles in the end code.
Note: Most of the material in this article is taken from codeguru.com
Comments
people
people
people
people
people
people
people
people