Understanding Decrement Operator in C | Tutorial: Post Decrement and Pre Decrement Operators with Examples
Decrement Operator :
- The Decrement operator Decrements the Value of the variable by 1 (by Subtracting 1 from it’s Current Value).
- Decrement Operator is Unary operator. That means Decrement operator is operates on only one Operand.
- Decrement Operator have Highest priority than all Binary Operators. Because it is unary operator and Unary operators have higher priority than all Binary operators. You can see Full priority table here C operators Priority table.
- Decrement Operator can not work on Constants. it can be apply only on Variables.
- Decrement Operator Denoted by — Symbol.
- Ex : –X (pre decrement) or X– (Post Decrement).
Different Types of Decrement operators :
- pre-Decrement operator (or) prefix decrement operator.
- post-Decrement operator (or) postfix decrement operator.
Pre-decrement Operator :
- In pre-decrement operator, Operator is written before the operand.
- Pre-decrement operator decrements the value of variable first, then decremented value is used to evaluate the Expression.
-
a= 5;
-
y = —a;
Post-Decrement Operator :
- In post-decrement operator, Operator is written after the Operand.
- Post-decrement operator first expression is Evaluated and then value of Variable is decremented. that means decremented value is not used in expression.
-
a= 5;
-
y = a–;
Example program 1 : C program to Understand decrement operator
-
#include<stdio.h>
-
int main(void)
-
{
-
int x=8,y=10;
-
printf(“x=%dt“,x);
-
printf(“x=%dt“,–x); /*Prefix decrement*/
-
printf(“x=%dt“,x);
-
-
printf(“y=%dt“,y);
-
printf(“y=%dt“,y—); /*Postfix decrement*/
-
printf(“y=%dt“,y);
-
return 0;
-
}
1 2 |
<b>x=8 x=7 x=7 y=10 y=10 y=9 </b> |
Example 2 : program to understand Decrement Operator in C
-
#include<stdio.h>
-
void main()
-
{
-
int a,b,c=5,d=5;
-
a = c–;
-
b = —d;
-
printf(“Value of a : %d”,a);
-
printf(“Value of b : %d”,b);
-
printf(“Value of c : %d”,c);
-
printf(“Value of d : %d”,d);
-
}
output :
1 2 3 4 |
<b>Value of a : 5 Value of b : 4 Value of c : 4 Value of d : 4</b> |
Example 3 : Decrement Operator can not be used on Constants
-
#include<stdio.h>
-
void main()
-
{
-
int a;
-
a = 10–;
-
}
Compilation error time: 0 memory: 2248 signal:0
1 2 |
<b>prog.c: In function ‘main’: prog.c:5:8: error: lvalue required as decrement operand</b> |
1 Response
[…] Decrements Operators and Pre and post decrements […]