65.9K
CodeProject is changing. Read more.
Home

Increment/Decrement operators

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.40/5 (3 votes)

Mar 2, 2010

CPOL
viewsIcon

20031

When incrementing or decrementing a variable, favor prefix operators over postfix operators if you do not need the value of the expression.Example:void foo(std::vector intvec){ for (std::vector::iterator it = intvec.begin(); it != intvec.end(); ++it) { // do something ...

When incrementing or decrementing a variable, favor prefix operators over postfix operators if you do not need the value of the expression. Example:
void foo(std::vector intvec)
{
   for (std::vector::iterator it = intvec.begin(); it != intvec.end(); ++it)
   {
      // do something
   }
}
The reason for this is that postfix operators (such as it++) need to create a copy of the original variable. This copy is being used as a placeholder that later can be used as the value of the postfix expression. A prefix operator does not need to do that, as the value of a prefix increment or decrement expression is the value of the variable after the operation. The cost of creating an additional temp might be trivial for integral types, but often ++/-- operators are defined for non-trivial types, and by their very nature they are being used in loop constructs.