Assignment Operators

What Are ++i and i++ in C?

The ++i and i++ operators both add one to a variable, but ++i uses the new value and i++ uses the old one. Examples show the difference in C.

On this page
  1. The short answer
  2. Prefix and postfix
  3. When they do the same thing
  4. Why ++i can matter more for classes
  5. Avoid changing a variable twice in one expression
  6. Unary operators in C

The short answer

++i and i++ both add 1 to the variable i. The difference is which value the expression gives back. ++i increments first and gives the new value. i++ gives back the old value and then increments.

Prefix and postfix

The prefix form, ++i, goes before the variable. The variable goes up by one, and the expression has the new value.

The postfix form, i++, goes after the variable. The expression has the value i held before the increment, and then i goes up by one.

This small program shows both forms:

#include <stdio.h>

int main(void) {
    int a = 5;
    int b = ++a;  /* a becomes 6 first, then b gets 6 */
    int c = a++; /* c gets 6 first, then a becomes 7 */

    printf("a=%d b=%d c=%d\n", a, b, c);  /* prints a=7 b=6 c=6 */
    return 0;
}

When they do the same thing

On its own, ++i; and i++; do the same thing. The difference only shows up when the value is used. Many programmers write the prefix form in loops out of habit:

for (int i = 0; i < 3; ++i) {
    /* runs three times */
}

Why ++i can matter more for classes

For a plain int, compilers usually produce the same machine code either way. For class types such as iterators, the postfix form has to keep a copy of the old object before it increments, so ++i may avoid that extra copy.

Avoid changing a variable twice in one expression

Expressions such as i = i++ + 1; change i more than once and are hard to read. In C, this has undefined behavior, so the result cannot be relied on. Put each change on its own line instead.

Unary operators in C

Both ++ and -- are unary operators in C, which means each one works on a single operand. --i and i-- follow the same rules as ++i and i++, except that they subtract 1.

The complete guide to assignment operators

Assignment Operators in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

Bitwise XOR in C++

Learn how the bitwise XOR operator (^) in C++ works, with a truth table, code examples, and common uses such as toggling bits and swapping values.

Recursive Functions in C++

A recursive function calls itself to solve smaller parts of a problem. Learn the base case, the recursive case, examples in C++ and when to use recursion.

Recursion 5 min read