Quick links
Increment and Decrement operator are used to increment or decrement value by 1.
There are two variants of increment/decrement operator.
- Prefix (pre-increment and pre-decrement)
- Postfix (post-increment and post-decrement)
Syntax of increment/decrement operator
Syntax | Description | Example |
---|---|---|
++<variable-name> | Pre increment | ++a |
<variable-name>++ | Post increment | a++ |
--<variable-name> | Pre decrement | --a |
<variable-name>-- | Post decrement | a-- |
Important note: ++
and --
operators are used with variables. Using ++
or --
with constant will result in error. Such as expressions like 10++
, (a + b)++
etc. are invalid and causes compilation error.
Let us consider an integer variable int a = 10;
. To increment a by 1, you can use eithera = a + 1
(Simple assignment)a += 1
(Shorthand assignment)a++
(Post increment)++a
(Pre increment)
Result of all the above code are similar.
Prefix vs Postfix
Both prefix and postfix does same task of incrementing/decrementing the value by 1. However, there is a slight difference in order of evaluation.
Prefix first increment/decrements its value then returns the result. Whereas postfix first returns the result then increment/decrement the value.
To understand this efficiently let’s consider an example program
#include <stdio.h>
int main()
{
int a, b, c;
a = 10; // a = 10
b = ++a; // a=11, b=11
c = a++; // a=12, c=11
printf("a=%d, b=%d, c=%d", a, b, c);
return 0;
}
Output of above program is a=12, b=11, c=11. Let us understand the code.
a = 10
Assigns 10 to variable ab = ++a
Since we have used prefix notation. Hence, first it increments the value of a to 11, then assigns the incremented value of a to b.c = a++
Here we have used postfix notation. Hence, first it assigns the current value of a i.e. 11 to c, then increments the value of a to 12.
Important note: Never use postfix and prefix operator at once otherwise it will result in error. Such as ++a++
, ++a--
both results in compilation error.