# function of increment/decrement operators and their varieties.

**Q2. What is the function of increment/decrement operators? How many varieties do they come in? How are these two varieties different from one another?**

**Ans. **The operator ++ adds 1 to its operand, and – subtracts one. In other words,

a = a + 1;

is the same as:

++a; or a++;

And

a = a- 1;

is the same as

–a; or a–;

However, both the increment and decrement operators come in two varieties: they may either precede or follow the operand. The **prefix** version comes before the operand (as in ++a or –a) and the **postfix** version comes after the operand (as in a++ or a–). The two versions have the same effect upon the operand, but they differ when they take place in an expression.

**Working with prefix version**

When an increment or decrement operator precedes in operand (that is, in its prefix form), C++ performs the increment or decrement operation before using the value of the operand.

For example, the expression

sum = sum + (++count);

will take place in the following fashion. (Assuming the initial values of sum and count are 0 and 10 respectively).

sum sum count

- 0 10 Initial values
- 0 11 First increment it

11 = 0 + 11 Now use it

The prefix increment or decrement operators follow **change-then-use** rule, that is, they first change (increment or decrement) the value of their operand, then use the new value in evaluating the expression.

**Working with postfix version**

When an increment or decrement operator follows its operand (that is, in its postfix form), C++ first uses the value of the operand in evaluating the expression before incrementing or decrementing the operand’s value.

For example, the expression

sum = sum + count++;

will take place in the following fashion. (Assuming the initial values of sum and count are 0 and 10 respectively).

sum sum count

- 0 10 Initial values;

10 0 10 First use it

10 = 0 + 11 Now increment it

The postfix increment or decrement operators follow **use-then-change** rule, that is, they first use the value of their operand in evaluating the expression and then change (increment or decrement) the operand’s value.