C Increment & Decrement
In this page:
Prefix Increment
Prefix increment (++x) adds 1 to the variable's value first, and the expression it's part of then uses that already-updated value -- so y = ++x; gives y the value of x after the increase.
Example: Prefix Increment
#include <stdio.h>
int main() {
int x = 5;
int y = ++x;
printf("%d %d", x, y);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Postfix Increment
Postfix increment (x++) uses the variable's current value in the surrounding expression first, and only applies the +1 increase afterward -- so y = x++; gives y the value x had *before* it was incremented.
Example: Postfix Increment
#include <stdio.h>
int main() {
int x = 5;
int y = x++;
printf("%d %d", x, y);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Prefix Decrement
Prefix decrement (--x) subtracts 1 first and the updated value is what gets used in the expression, mirroring prefix increment but decreasing instead of increasing the value.
Example: Prefix Decrement
#include <stdio.h>
int main() {
int x = 5;
int y = --x;
printf("%d %d", x, y);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Postfix Decrement
Postfix decrement (x--) uses the current value in the expression first, then decreases the variable afterward -- mirroring postfix increment's timing but subtracting instead of adding.
Example: Postfix Decrement
#include <stdio.h>
int main() {
int x = 5;
int y = x--;
printf("%d %d", x, y);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Mixing in Expressions
Mixing several increment/decrement operators inside one complex expression (like x++ + ++x) leads to undefined or compiler-dependent behavior in C -- it's best practice to keep such operators in their own separate statement.
Example: Mixing in Expressions
#include <stdio.h>
int main() {
int x = 5;
x++;
++x;
printf("%d", x);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: