Increment and Decrement Operator
Increment Operator
When we use the increment operator, we add the given value.
int main()
{
int x=5;
printf("x=%d",x);
x++;
printf("x=%d",x);
return 0;
}
Output:
5
6
Decrement Operator
When we use the decrement operator, we add and subtract one from the given value.
int main()
{
int x=5;
printf("x=%d",x);
x--;
printf("x=%d",x);
return 0;
}
Output:
5
4
post increment:
int x=5;
int y=x++;
Description:
step 1:
First the value of integer variable x is stored in memory.
step 2:
int y=x++;
First the value of x is stored in y. That is, the value of 5 in x is stored in y. Now the value of y is 5. Step 3:
Only after the value of x is stored in y, the operation x++(x+1) takes place. That is, x is adding one (1) to the value it has. Now, the existing value of 5 is changed to the value of 6 and stored in the memory.
pre increment
int x=5;
int y=++x;
Description:
step 1:
First the value of variable x is stored in memory.
step 2:
int y=++x;
Here the value of x is first added to the value of one (1). Then, the value of 5 in x is changed to 6.
Step 3:
Now the value of x is stored in y. That is, the value of 6 in x is stored in y.