Previously we had seen the various arithmetic operators in C++. Now let us have a look at two new operators called the increment (++) and decrement (- -) operators.

Both these operators are unary operators. That means they work only on one operand.

They can be used in two ways :
1. Prefix form
2. Postfix form

Let us see each of these operators in both the forms stated above.

1. INCREMENT OPERATOR (++)

The increment operator increments the value of a variable. Consider the following program :

This code first increments value of ‘a’ using ‘a++’ and prints 6.

Then it again increments value of ‘a’ using ‘++a’ and thus 7 is printed.

So here both prefix and postfix forms work the same way.

Now let us consider another program to see the difference between these two.

In the program above, when the first cout statement is executed it prints value 5 which is the original value of ‘a’.

When the next cout statement executes then also value 5 is printed and not 6. This is because a++; is in postfix form. In the postfix form, the value of the variable is first used in a statement and then it is changed. So first 5 is printed and then 5 in incremented to 6.

So when the third cout statement executes, value 6 is printed.

Now the next statement uses prefix form ++a ; In the prefix form, the value of the variable is first changed and then used in a statement. So first value of ‘a’ (which became 6 previously) is incremented to 7 and then it is printed.

Lastly, we again print value of ‘a’ which is 7.

2. DECREMENT OPERATOR

The decrement operator decrements the value of a variable by 1.

It is used in the same way as the increment operator in the postfix and prefix forms.

Following program shows its working.

Hope you’re clear with these two operators. Drop your queries in comments below.




Tags: , , , , , , ,

Leave A Response