Decrement Operator : C Programming [Post Decrement / Pre Decrement]
We have seen increment operator in C Programming which increments the value of the variable by 1. Similarly C Supports one more unary operator i.e decrement operator which behaves like increment operator but only difference is that it decreases the value of variable by 1.
Decrement Operator in C Programming :
- Decrement operator is used to decrease the current value of variable by subtracting integer 1.
- Like Increment operator, decrement operator can be applied to only variables.
- Decrement operator is denoted by -.
Different Types of Decrement Operation :
When decrement operator used in C Programming then it can be used as pre-decrement or post-decrement operator.
A. Pre Decrement Operator in C Programming :
Pre-decrement operator is used to decrement the value of variable before using in the expression. In the Pre-decrement value is first decremented and then used inside the expression.
b = --var;
Suppose the value of variable var is 10 then we can say that value of variable ‘var’ is firstly decremented then updated value will be used in the expression.
B. Post Decrement Operator in C Programming :
Post-decrement operator is used to decrement the value of variable immediatly after executing expression completely in which post decrement is used. In the Post-decrement old value is first used in a expression and then old value will be decrement by 1.
b = var--;
Value of variable ‘var’ is 5. Same value will be used in expression and after execution of expression new value will be 4.
Live Program : C Program to Perform Decrement Operation in C Programming
#include<stdio.h> void main() { int a,b,x=10,y=10; a = x--; b = --y; printf("Value of a : %d",a); printf("Value of b : %d",b); }
Output :
Value of a : 10 Value of b : 9
Tip #1 : Decrement Operator should not be used on Constants
We cannot use decrement operator in the following case -
b = --5;
Or
b = 5--;