C increment operator
In C Programming , Unary operators are having higher priority than the other operators. Unary Operators are executed before the execution of the other operators. Increment and Decrement are the examples of the Unary operator in C.
Increment Operator in C Programming
- Increment operator is used to increment the current value of variable by adding integer 1.
- Increment operator can be applied to only variables.
- Increment operator is denoted by ++.
Different Types of Increment Operation
In C Programming we have two types of increment operator i.e Pre-Increment and Post-Increment Operator.
A. Pre Increment Operator
Pre-increment operator is used to increment the value of variable before using in the expression. In the Pre-Increment value is first incremented and then used inside the expression.
b = ++y;
In this example suppose the value of variable ‘y’ is 5 then value of variable ‘b’ will be 6 because the value of ‘y’ gets modified before using it in a expression.
B. Post Increment Operator
Post-increment operator is used to increment the value of variable as soon as after executing expression completely in which post increment is used. In the Post-Increment value is first used in a expression and then incremented.
b = x++;
In this example suppose the value of variable ‘x’ is 5 then value of variable ‘b’ will be 5 because old value of ‘x’ is used.
Sample program
#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 : 11
Tip #1 : Increment Operator should not be used on Constants
We cannot use increment operator on the constant values because increment operator operates on only variables. It increments the value of the variable by 1 and stores the incremented value back to the variable,
b = ++5;
Or
b = 5++;
Summary : Expression Solving using Pre/Post Increment
[box]When Postfix (++) is used with a variable in an Expression ,The Expression is evaluated first using the original value of variable and then variable is incremented by one[/box]