Easy Tutorial
❮ Cpp While Loop Cpp Web Programming ❯

C++ Increment and Decrement Operators

C++ Operators

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

x = x+1;

is equivalent to

x++;

Similarly:

x = x-1;

is equivalent to

x--;

Both the increment and decrement operators can be placed before (prefix) or after (suffix) the operand. For example:

x = x+1;

can be written as:

++x; // prefix form

or:

x++; // suffix form

There is a slight difference between the prefix and suffix forms. If the prefix form is used, the increment or decrement is performed before the expression is evaluated. If the suffix form is used, the increment or decrement is performed after the expression is evaluated.

Example

Consider the following example to understand the difference between the two:

Example

#include <iostream>
using namespace std;

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

   // The value of a is not incremented before the assignment
   c = a++;   
   cout << "Line 1 - Value of a++ is :" << c << endl ;

   // After the expression is evaluated, the value of a is incremented by 1
   cout << "Line 2 - Value of a is :" << a << endl ;

   // The value of a is incremented before the assignment
   c = ++a;  
   cout << "Line 3 - Value of ++a is  :" << c << endl ;
   return 0;
}

When the above code is compiled and executed, it produces the following result:

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

C++ Operators

❮ Cpp While Loop Cpp Web Programming ❯