DEV Community

Kerimova_Manzura
Kerimova_Manzura

Posted on

C++ Increment and Decrement Operators

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

x = x+1;

is the same as

x++;
Enter fullscreen mode Exit fullscreen mode

And similarly −

x = x-1;

is the same as

x--;
Enter fullscreen mode Exit fullscreen mode

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

x = x+1;

can be written as

++x; // prefix form
Enter fullscreen mode Exit fullscreen mode

or as −

x++; // postfix form
Enter fullscreen mode Exit fullscreen mode

When an increment or decrement is used as part of an expression, there is an important difference in prefix and postfix forms. If you are using prefix form then increment or decrement will be done before rest of the expression, and if you are using postfix form, then increment or decrement will be done after the complete expression is evaluated.
In programming (Java, C, C++, JavaScript etc.), the increment operator ++ increases the value of a variable by 1. Similarly, the decrement operator -- decreases the value of a variable by 1.

#include <iostream>

using namespace std;

int main() {
   int var1 = 5, var2 = 5;

   // 5 is displayed
   // Then, var1 is increased to 6.
   cout << var1++ << endl;

   // var2 is increased to 6
   // Then, it is displayed.
   cout << ++var2 << endl;

   return 0;
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)