Increment and Decrement Operators (Prefix and Postfix Operator) - WAY2IT

Latest Post :

Home Top Ad

Increment and Decrement Operators (Prefix and Postfix Operator)



The increment operator ++ adds 1 to its operand, and the decrement operator -- subtracts 1 from its operand.

Suppose, a = 5 then,
++a;          //a becomes 6
a++;          //a becomes 7
--a;          //a becomes 6
a--;          //a becomes 5


Syntax :
Increment operator  : ++var_name; (or) var_name++;
Decrement operator  : –-var_name; (or) var_name –-;

Example :
Increment operator :  ++x; (or) x++;
Decrement operator :  ––x; (or) x––;

Both the increment and decrement operators can either precede (prefix) or follow (postfix) the operand.
For example:

Prefix :
++x;
--x;

Postfix :
x++;
x--;

All are the same :
x = x + 1;
x += 1;
x++;

Note : Increment and decrement operators are can not apply on constant.

x= 4++;  // gives error, because 4 is constant

 
 

Example :


main()
{
   int a = 20;
   int c ;

   // Value of a will not be increased before assignment.
   c = a++;  
   cout << "Line 1 - Value of a++ is : " << c << endl ;

   // After expression value of a is increased
   cout << "Line 2 - Value of a is : " << a << endl ;

   // Value of a will be increased before assignment.
   c = ++a; 
   cout << "Line 3 - Value of ++a is  : " << c << endl ;
   return 0;
}


Output :

Line 1 - Value of a++ is : 20
Line 2 - Value of a is : 21
Line 3 - Value of ++a is : 22