![]() |
VOOZH | about |
In C/C++, Increment operators are used to increase the value of a variable by 1. This operator is represented by the ++ symbol.
The increment operator can be classified into two types:
The pre and post-increment operators in C perform the same task, but have different operator precedence. Understanding pre-increment and post-increment operators is essential for controlling variable values.
A pre-increment operator is used to increment the value of a variable before using it in an expression. In the Pre-Increment, value is first incremented and then used inside the expression.
Syntax:
Here, if the value of ‘x’ is 10 then the value of ‘a’ will be 11 because the value of ‘x’ is incremented before assigning it to 'a'.
The above expression can be as equivalent to
Pre-Increment Operator in C Program
x = 11 Assigning x to a with Pre Increment Operation a = 11 x = 11
A post-increment operator is used to increment the value of the variable after executing the expression completely in which post-increment is used. In the Post-Increment, value is first used in an expression and then incremented.
Syntax:
Here, suppose the value of ‘x’ is 10 then the value of variable ‘a’ will be 10 because the values of x is assigned to 'a' before the incrementation operation, thus the old value of ‘x’ is used.
The above expression can be considered equivalent to
Post-Increment Operator in C Program
x = 11 Assigning x to a with Post Incrementation a = 10 x = 11
Special Case for Post-increment operator: If we assign the post-incremented value to the same variable then the value of that variable will not get incremented i.e. it will remain the same like it was before.
Syntax:
Here, if the value of ‘x’ is 10 then the value of ‘a’ will be 10 because the value of ‘x’ gets assigned to the post-incremented value of 'x'.
Value of x : x = 10 Assigning x to x with Post-incrementation x = 10 //No change in value of x
Note: This special case is only with post-increment and post-decrement operators, while the pre-increment and pre-decrement operators works normal in this case.
The precedence of postfix ++ is more than prefix ++ and their associativity is also different. Associativity of prefix ++ is right to left and associativity of postfix ++ is left to right.