Increment and Decrement Operator in C
There are two such operators.
- Increment operator is represented by ‘++’. This operator adds 1 to the value with which it is written. For example, y++ and ++y will add 1 to the ‘y’.
- Decrement operator is represented by ‘–’.This operator subtracts 1 from the value with which it is written. For example, y–, and –y will subtract 1 from the ‘y’.
Both operators are used in two ways:
Postfix: a++ increases the value of ‘a’ by 1. a—subtracts 1 from that value.
Prefix: ++a increases the value of ‘a’ by 1.–a decreases the value of a by 1.
Difference between prefix and postfix in C
In a++, we get the original value of ‘a’ first, then it will get incremented. But ++a first increases the value of ‘a’ by 1 and returns the same incremented value of ‘a’. The same as with a– and –a.
Example
#include<stdio.h> int main() { int a=100; int b=200; int c=300; int d=400; printf("value of a++ = %d\n",a++); printf("value of ++b = %d\n",++b); printf("value of c-- = %d\n",c--); printf("value of --d = %d\n",--d); }
Output
In a++, ‘100’ is printed, and then the value gets incremented.
In ++b, ‘201’ is printed because 1 is added to 200, and it gets displayed.
The same occurs with variables c and d.