C++ Postfix Increment and Decrement Operators

C++ provides prefix and postfix increment and decrement operators; this section describes only the postfix increment and decrement operators. (For more information, see Increment and Decrement Operators.) The difference between the two is that in the postfix notation, the operator appears after postfix-expression, whereas in the prefix notation, the operator appears before expression. The following example shows a postfix-increment operator:

i++

The effect of applying the postfix increment, or “postincrement,” operator (++) is that the operand’s value is increased by one unit of the appropriate type. Similarly, the effect of applying the postfix decrement, or “postdecrement,” operator (––) is that the operand’s value is decreased by one unit of the appropriate type.

For example, applying the postincrement operator to a pointer to an array of objects of type long actually adds four to the internal representation of the pointer. This behavior causes the pointer, which previously referred to the nth element of the array, to refer to the (n+1)th element.

The operands to postincrement and postdecrement operators must be modifiable (not const) l-values of arithmetic or pointer type. The result of the postincrement or postdecrement expression is the value of the postfix-expression prior to application of the increment operator. The type of the result is the same as that of the postfix-expression, but it is no longer an l-value.

The following code illustrates the postfix increment operator.

if( var++ > 0 )
    *p++ = *q++;

In this example, the variable var is compared to 0, then incremented. If var was positive before being incremented, the next statement is executed. First, the value of the object pointed to by q is assigned to the object pointed to by p. Then, q and p are incremented.

Postincrement and postdecrement, when used on enumerated types, yield integral values. Therefore, the following code is illegal:

enum Days {
    Sunday = 1,
    Monday, 
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
};

void main()
{
  Days Today = Tuesday;
  Days SaveToday;

  SaveToday = Today++;  // error
}

The intent of this code is to save today’s day and then move to tomorrow. However, the result is that the expression Today++ yields an int — an error when assigned to an object of the enumerated type Days.