Increment/decrement operators
Increment/decrement operators are unary operators that increment/decrement the value of a variable by 1.
They can be applied either postfix:
a++
a--
or prefix:
++a
--a
The returned result of the postfix version of the operator is the original operand, with a side-effect being that the operand is incremented/decremented after this result is returned.
The returned result of the prefix version of the operator is the incremented/decremented operand.
Therefore, the following lines all result in a being incremented by 1:
a = a + 1;
a += 1;
a++;
++a;
But, the value of b is not equal to the value of c after the execution of the following lines:
int a = 1;
int b = a++; // after execution: a equals 2, b equals 1
a = 1;
int c = ++a; // after execution: a equals 2, c equals 2
[edit] Example
#include <stdlib.h> #include <stdio.h> int main(void) { int a = 1; int b = 1; // Behaviour of the postfix increment and decrement operators. printf("\n"); printf("original values: a == %d, b == %d\n", a, b); printf("result of postfix operators: a++ == %d, b-- == %d\n", a++, b--); printf("after postfix operators applied: a == %d, b == %d\n", a, b); // Reset a and b. a = 1; b = 1; // Behaviour of the prefix increment and decrement operators. printf("\n"); printf("original values: a == %d, b == %d\n", a, b); printf("result of prefix operators: ++a == %d, --b == %d\n", ++a, --b); printf("after prefix operators applied: a == %d, b == %d\n", a, b); printf("\n"); return EXIT_SUCCESS; }
Output:
original values: a == 1, b == 1 result of postfix operators: a++ == 1, b-- == 1 after postfix operators applied: a == 2, b == 0 original values: a == 1, b == 1 result of prefix operators: ++a == 2, --b == 0 after prefix operators applied: a == 2, b == 0
[edit] Notes
Because of the side-effects involved, built-in increment and decrement operators must be used with care to avoid undefined behavior due to violations of sequencing rules.
[edit] See Also
Common operators | ||||||
---|---|---|---|---|---|---|
assignment | increment decrement |
arithmetic | logical | comparison | member access |
other |
a = b |
++a |
+a |
!a |
a == b |
a[b] |
a(...) |