Increment and Decrement Operators (++, --)

The prefix increment operator (++), also called the “preincrement” operator, adds one to its operand; this incremented value is the result of the expression. The operand must be an l-value not of type const. The result is an l-value of the same type as the operand.

The prefix decrement operator (––), also called the “predecrement” operator, is analogous to the preincrement operator, except that the operand is decremented by one and the result is this decremented value.

Both the prefix and postfix increment and decrement operators affect their operands. The key difference between them is when the increment or decrement takes place in the evaluation of an expression. (For more information, see Postfix Increment and Decrement Operators.) In the prefix form, the increment or decrement takes place before the value is used in expression evaluation, so the value of the expression is different from the value of the operand. In the postfix form, the increment or decrement takes place after the value is used in expression evaluation, so the value of the expression is the same as the value of the operand.

An operand of integral or floating type is incremented or decremented by the integer value 1. The type of the result is the same as the operand type. An operand of pointer type is incremented or decremented by the size of the object it addresses. An incremented pointer points to the next object; a decremented pointer points to the previous object.

This example illustrates the unary decrement operator:

if( line[--i] != '\n' )
    return;

In this example, the variable i is decremented before it is used as a subscript to line.

Because increment and decrement operators have side effects, using expressions with increment or decrement operators in a macro can have undesirable results (see Macros in the Preprocessor Reference for more information about macros). Consider this example:

#define max(a,b) ((a)<(b))?(b):(a)

...

int i, j, k;

k = max( ++i, j );

The macro expands to:

k = ((++i)<(j))?(j):(++i);

If i is greater than or equal to j, it will be incremented twice.

Note   C++ inline functions are preferable to macros in many cases because they eliminate side effects such as those described here, and allow the language to perform more complete type checking.