C Increment and Decrement Operators – Make Counters Easy
In C programming, increment (++
) and decrement (--
) operators are used to increase or decrease a variable’s value by 1. They’re compact and commonly used in loops, counters, and algorithms.
Types of Increment and Decrement Operators
Operator | Description |
---|---|
++ | Increments value by 1 |
-- | Decrements value by 1 |
These can be used in two forms:
Prefix (
++x
,--x
)Postfix (
x++
,x--
)
Pre-Increment and Post-Increment
Pre-Increment (++x
)
Increments the value before it’s used in an expression.
int x = 5;
int y = ++x; // x becomes 6, then y is assigned 6
Post-Increment (x++
)
Uses the value first, then increments it.
int x = 5;
int y = x++; // y is assigned 5, then x becomes 6
Pre-Decrement and Post-Decrement
Pre-Decrement (--x
)
Decreases the value before use.
int x = 5;
int y = --x; // x becomes 4, then y = 4
Post-Decrement (x--
)
Uses the value, then decreases it.
int x = 5;
int y = x--; // y = 5, then x becomes 4
Full Example
#include <stdio.h>
int main() {
int a = 5, b, c;
b = ++a; // Pre-increment: a becomes 6, b = 6
printf("After pre-increment: a = %d, b = %d\n", a, b);
c = a++; // Post-increment: c = 6, then a becomes 7
printf("After post-increment: a = %d, c = %d\n", a, c);
--a; // Pre-decrement: a becomes 6
printf("After pre-decrement: a = %d\n", a);
a--; // Post-decrement: a becomes 5
printf("After post-decrement: a = %d\n", a);
return 0;
}
Output:
After pre-increment: a = 6, b = 6
After post-increment: a = 7, c = 6
After pre-decrement: a = 6
After post-decrement: a = 5
Use Cases / Example
Loop
for(int i = 0; i < 10; i++) {
printf("%d ", i);
}
Best Practices
Tip | Why It Helps |
---|---|
Prefer ++i in loops | Often more efficient in C (minor gain) |
Avoid using ++ and -- in complex expressions | Reduces confusion |
Use increment/decrement sparingly in conditions | Increases readability |
Common Mistakes
Mistake | Problem |
---|---|
Using x++ in printf() and expecting updated value | Outputs old value |
Using multiple increments in one statement | Leads to undefined behavior |