C Language Pre-increment and Post-increment Operators
#include <stdio.h>
int main()
{
int a = 1, b = 1, x = 0, y = 0;
double w;
x = 1 + a++;
printf("x = %d\n", x);
printf("a = %d\n", a);
y = ++b;
printf("y = %d\n", y);
printf("b = %d\n", b);
}
Pre-increment means increment variable before its value is used. Post-increment means increment variable after its value has been used. To understand how these operators work, let's look at the first case:
a = 1;
x = 1 + a++; // ++ on right means post-increment
First you're setting the value of a
to 1
. Then you're saying add a
(value is 1
) to x
(value is 1
). The result is x
has a value of 2
. And then, after the statement is done executing, as a side-effect, a
is incremented, because you used the post-increment form of ++
. So after x
has been set to a value of 2
, the value of a
will become 2
.
Instead, if you used a a pre-increment operator:
a = 1;
x = 1 + (++a); // ++ on left means pre-increment
Again, you start with a = 1
, but this time, a
is incremented before its value is used in the statement, because ++
on the left-side means pre-increment. In other words, first, a
is incremented to the value of 2
. Then a
is added to x
(whose value is 1
), setting the value of x
to 3
.
In both the above cases, a
starts out with a value of 1
and becomes 2
. The difference is whether that happens before or after the value of a
is used in the expression.