Yves M
February 13th, 2003, 01:18 PM
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.
// Prefix operators are preferred in cases in the following common cases:
for (;checkstate(x);++x) dosomething(x);
++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:
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;
}
};
FAQ contributed by: [Kevin Hall (http://www.codeguru.com/forum/member.php?u=85152)]
<br><br>
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.
// Prefix operators are preferred in cases in the following common cases:
for (;checkstate(x);++x) dosomething(x);
++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:
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;
}
};
FAQ contributed by: [Kevin Hall (http://www.codeguru.com/forum/member.php?u=85152)]
<br><br>