Increment Operator (++) and Decrement Operator (--):


In certain situations, there is a need to increase or decrease the value of an operand by 1. C provides an increment operator (++) and a decrement operator (--) to increase and decrease the value of the operand by 1 respectively. If i is a variable then ++i is equivalent to i = i + 1. This means that value of variable i is increased by 1. Similarly i- - equivalent to i = i  - 1. This means that value of a variable i is decreased by 1.

These are two ways of representing increment and decrement operators.
i)                    As a prefix i.e. operator precedes the variable. E.g. ++i, - -i.
ii)                  As a postfix i.e. operator follows the variable. E.g. i++, i- -.

In case of prefix increment operator (E.g. ++i), the value of the variable will first be incremented before it is used in the expression in which it appears.

In case of postfix increment operator (E.g. i++), the current value of the variable is used in the expression in which it appears and then value is incremented by 1.
We use the increment and decrement operators in for and while loops extensively.


Rules for ++ and – Operators:
1.      Increment and decrement operators are unary operators and they require variable as their operands.
2.      When postfix ++ (or--) is used with a variable in expression, the expression is evaluated first using the           original value of the variable and then the variable is incremented (or decremented) by one.
3.      When prefix ++ (or --) is used in expression, the variable is incremented (or decremented) first and then        the expression is evaluated using the value of the variable

4.      The precedence and associatively of ++ and – operators are the same as those of unary + and unary -..

Previous                                                                                    Next


Powered by Blogger.