Understanding Pre and Post Increment/Decrement in C

This article is a complementary resource to the Learn C Programming Course.

Understanding Pre and Post Increment/Decrement in C

In C, the increment (++) and decrement (--) operators are used to modify the value of a variable by one.

These operators can be used in two ways:

  1. pre-increment/pre-decrement
  2. post-increment/post-decrement.

While they may seem similar, their behavior differs significantly depending on where they are placed relative to the variable.

This article explores the differences between these operators and provides examples to clarify their usage.


1. Pre Increment (++x) and Pre Decrement (--x)

#include <stdio.h>

int main() {
    int x = 5;

    // Pre-increment: x is incremented to 6, then assigned to y
    int y = ++x; 

    printf("x = %d, y = %d\n", x, y);

    int a = 10;
    // Pre-decrement: a is decremented to 9, then assigned to b
    int b = --a; 

    printf("a = %d, b = %d\n", a, b);

    return 0;
}

Output

x = 6, y = 6
a = 9, b = 9

Here,

  1. In int y = ++x, x is incremented to 6 before being assigned to y.
  2. In int b = --a, a is decremented to 9 before being assigned to b.

The overall behavior of the pre increment/decrement can be summarized as:

  1. The value of the variable is modified first.
  2. The updated value is then used in the expression.

2. Post-increment (x++) and Post-decrement (x--)

#include <stdio.h>

int main() {
	int x = 5;

           // y is assigned the current value of x (5), then x is incremented to 6
	int y = x++;

	printf("x = %d, y = %d\n", x, y);

	int a = 10;
 
           // b is assigned the current value of a (10), then a is decremented to 9
	int b = a--; 

	printf("a = %d, b = %d\n", a, b);

	return 0;
}

Output

x = 6, y = 5
a = 9, b = 10

Here,

  1. In int y = x++, y is assigned the current value of x (5), and then x is incremented to 6.
  2. In int b = a--, b is assigned the current value of a (10), and then a is decremented to 9.

The overall behavior of the post increment/decrement can be summarized as:

  1. The current value of the variable is used in the expression first.
  2. The value of the variable is modified after the expression is evaluated.