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.
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:Code:// Prefix operators are preferred in cases in the following common cases: for (;checkstate(x);++x) dosomething(x); ++x;
FAQ contributed by: [Kevin Hall]Code:class MyClass { public: MyClass& operator++() //Prefix increment operator (++x) { //Perform increment operation return *this; } MyClass operator++(int) //Postfix increment operator (x++) { MyClass temp = *this; //Perform increment operation return temp; } };


Reply With Quote
Bookmarks