The increment ++
or decrement --
operator is a unary operator. It is use to increase or decrease the value of the operand by 1. There are two types of increment or decrement operators and they are:
i. pre-increment and pre-decrement operator
In pre-increment or pre-decrement operator the value of the operand gets increased before using it in expression. This operator is pre-fixed on the operand. Example:
consider a = 10 and x
x = ++a which is equivalent to x = 1 + a
In the above example the value of both the x and a will be 11.
Program example of preincrement/decrement operators
//An example of preincrement/decrement operators
#include<stdio.h>
int main()
{
int a=10, x=0;
x = ++a; //pre-increment
printf("pre-increment\n");
printf("x = %d \n",x);
printf("a = %d \n",a);
a=10, x=0;
x = --a; //pre-decrement
printf("pre-decrement\n");
printf("x = %d \n",x);
printf("a = %d \n",a);
return 0;
}
Output
pre-increment
x = 11
a = 11
pre-decrement
x = 9
a = 9
ii. post-increment and post-decrement operator
In post-increment or post-decrement operator the value of the operand gets increased after executing the expression completely in which the operator is used. This operator is post-fixed on the operand. Example:
consider a = 10 and x
x = a++ which is equivalent to x = a + 1
In the above example after executing it completely the value of x will be 10 and the value of a will be 11.
Program xample of postincrement/decrement operators
//An example of postincrement/decrement operators
#include<stdio.h>
int main()
{
int a=10, x=0;
x = a++; //post-increment
printf("post-increment\n");
printf("x = %d \n",x);
printf("a = %d \n",a);
a=10, x=0;
x = a--; //post-decrement
printf("post-decrement\n");
printf("x = %d \n",x);
printf("a = %d \n",a);
return 0;
}
Output
post-increment
x = 10
a = 11
post-decrement
x = 10
a = 9