C Reference ยท Operators and Expressions
Increment and decrement operators in C
Reference for the C increment (++) and decrement (--) operators: prefix versus postfix value, use with pointers, loops, and the undefined-behavior traps.
The operators ++ and -- add or subtract one from a modifiable lvalue. Each comes in two forms. The prefix form (++i) changes the object and yields the new value. The postfix form (i++) changes the object and yields the old value.
When the expression is a statement on its own (i++;) the two forms are equivalent. The difference shows only when the value is used, for example as an array index or as an argument.
int i = 5; int a = i++; /* a is 5, i is 6 */ int b = ++i; /* i is 7, b is 7 */
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
++ lvalue -- lvalue /* prefix */ lvalue ++ lvalue -- /* postfix */
| Form | Value of the expression | Side effect |
|---|---|---|
++x |
x + 1 (the new value) |
x becomes x + 1. |
x++ |
the old value of x |
x becomes x + 1. |
--x |
x - 1 |
x becomes x - 1. |
x-- |
the old value of x |
x becomes x - 1. |
Operand: a modifiable lvalue of integer, floating, or pointer-to-object type. ++5 and (a + b)++ do not compile. The result is not an lvalue in C.
Errors / undefined behavior: overflow of a signed integer (INT_MAX++) is undefined; unsigned types wrap. Modifying the same object twice, or modifying it and reading it, between sequence points is undefined (see below).
Usage notes
- Equal as statements.
i++;and++i;do the same; in C, modern compilers generate identical code. Pick one style, and many C programmers choose postfix inforheaders. - Never modify an object twice in one expression.
i = i++,a[i] = i++andi++ + i++are undefined or have unspecified order. See sequence points. - Pointer operands move by whole elements. For an
int *p,p++advances bysizeof(int)bytes. It must stay within the array or one past its end. - Precedence: postfix
++and--bind tighter than prefix and all other unary operators, so*p++means*(p++), and(*p)++increments the pointed-to value. - Floating-point operands are allowed but rarely wise: adding 1 to a large float may not change it.
- Unsigned decrement wraps:
for (unsigned i = n; i >= 0; i--)never ends, becausei >= 0is always true. Usewhile (i-- > 0)instead. - Volatile and atomic operands:
++on avolatileobject is a separate read and write; on an_Atomicobject it is a single atomic operation. - No overloading. Unlike C++,
++always means "add one to a scalar".