C Programming Increment Decrement Operators

Last modified by Microchip on 2023/11/09 09:06

The final two general arithmetic operators are the increment and decrement operators. Both are unary operators, so only one operand is required and they may be placed on either side of the operand. If the entire statement consists of just the operand and this operator, then whether the operator is prefixed or postfixed does not matter.

For example, x++; and ++x; yield the same results.

OperatorOperationExampleResult
++Incrementx++ 
++x
Use x then increment x by 1.
Increment x by 1, then use x.
--Decrementx-- 
--x
Use x then decrement x by 1.
Decrement x by 1, then use x.

Postfix Example

1
2
3
4
 x = 5;
 y = (x++) + 5;
// y = 10
// x = 6

Prefix Example

1
2
3
4
 x = 5;
 y = (++x) + 5;
// y = 11
// x = 6

However, if this operator is used as part of a larger expression, then the position of the operator becomes significant. When the operator is postfixed as in the example on the left, this means "use the value of x first when evaluating the expression, then increment x afterward". When it is prefixed as in the example on the right, this means "increment the value of x first, then use that new value in the evaluation of the expression."