CIncrement & Decrement

Increment & Decrement

C provides two convenient unary operators for adding or subtracting one from a variable: ++ (increment) and -- (decrement). Each comes in a prefix form (++x) and a postfix form (x++), which behave identically in terms of the final stored value but differ in what value the expression itself evaluates to.

Form

Syntax

Behavior

Prefix

++x

Increments x first, then the expression evaluates to the new value

Postfix

x++

The expression evaluates to the original value, then x is incremented

C
#include <stdio.h>

int main(void) {
    int x = 5;
    int prefixResult = ++x;  // x becomes 6, prefixResult is 6

    int y = 5;
    int postfixResult = y++; // postfixResult is 5, y becomes 6

    printf("%d %d\n", x, prefixResult);   // 6 6
    printf("%d %d\n", y, postfixResult);  // 6 5
    return 0;
}
Same Idea Applies to Decrement

C
int a = 5;
printf("%d\n", --a); // 4 (decrements first, then evaluates to 4)
printf("%d\n", a--); // 4 (evaluates to 4, then a becomes 3)
printf("%d\n", a);   // 3
Undefined Behavior: Multiple Side Effects on One Variable
i = i++ + ++i; is undefined behavior
This is a classic C interview-question trap. The expression i = i++ + ++i; modifies i more than once between two sequence points without a defined order for those modifications relative to each other. The C standard says the behavior in this case is undefined — the compiler is allowed to produce any result at all, and different compilers (or even the same compiler with different optimization flags) commonly produce different answers. There is no "correct" value to memorize; the real lesson is to never write code like this.

C
int i = 1;
i = i++ + ++i; // UNDEFINED BEHAVIOR — do not write this in real code

/* Instead, break it into separate, unambiguous statements: */
int j = 1;
int left = j++;   // left = 1, j becomes 2
int right = ++j;  // j becomes 3, right = 3
j = left + right; // j = 4, and every step is well-defined
As a rule of thumb: never read and modify the same variable more than once in an expression without an intervening sequence point (such as the end of a full statement, or the short-circuit points of &&, ||, and ,). If you find yourself combining ++/-- with other uses of the same variable in one expression, split it into multiple statements instead.
  • ++x/--x (prefix) update first, then yield the new value

  • x++/x-- (postfix) yield the old value, then update

  • Never use a variable more than once between sequence points when one of those uses modifies it — the behavior is undefined

  • When in doubt, write increments/decrements as their own statement