Understanding Pre and Post Increment/Decrement in C
This article is a complementary resource to the Learn C Programming Course.
This article is a complementary resource to the Learn C Programming Course.
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:
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.
#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,
int y = ++x, x is incremented to 6 before being assigned to y.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:
#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,
int y = x++, y is assigned the current value of x (5), and then x is incremented to 6.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: