Increment/Decrement Operators



Increment/Decrement Operators:
The increment operator(++) adds 1 to its operand and the decrement operator(--) subtracts 1 from it's operand.

eg, a=a+1 is equal to a++
and a=a-1 is equal to a--

Here a++ and a-- are postfix form of increment and decrement operators.
There are two types of increment/decrement operators:
1.Prefix increment/decrement
2.Postfix increment/decrement

1.Postfix increment/decrement
The postfix form of increment/decrement operators follows use-then-change rule.

With postfix increment/decrement operators, values of operand first used and then addition or subtraction occurs.

for example:
Let us say we have integer a =10,
If we use post increment i.e a++, the output will be as follows:

#include<iostream.h>
void main()
{
    int a=10;

    // After assigning 10 to variable b
   // a will be incremented and becomes 11
    int b = a++;
 
    cout<<b;  // output without post increment
    cout<<a;  //output after post increment 
}

Output :
10
11

For post decrement replace ++ to -- and output will be
10
9

1.Prefix increment/decrement
The postfix form of increment/decrement operators follows change-then-use rule.

With prefix increment/decrement operators, values of operand first increment or decrement and then use.

for example:
Let us say we have integer a =10,
If we use post increment i.e ++a, the output will be as follows:

#include<iostream.h>
void main()
{
    int a=10;

    // First a will be incremented to 11
   // then assigned to b
    int b = ++a;
 
    cout<<b;  // incremented value 11 assigned to b
    cout<<a;  // incremented value of a i.e 11
}

Output :
11
11

For pre decrement replace ++ to -- and output will be
9
9

Post a comment

0 Comments