Increment ++ and decrement -- Operators in C++

C++Server Side ProgrammingProgramming

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

x = x+1; is the same as x++;

And similarly,

x = x-1; is the same as x--;

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

x = x+1; can be written as ++x;

Note that, 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 resting of the expression, and if you are using postfix form, then increment or decrement will be done after the complete expression is evaluated.

  •  In the prefix version (i.e., ++i), the value of i is incremented, and the value of the expression is the new value of i. So basically it first increments then assigns a value to the expression.
  • In the postfix version (i.e., i++), the value of i is incremented, but the value of the expression is the original value of i. So basically it first assigns a value to expression and then increments the variable.

Example

Let's look at some code to get a better understanding −

#include<iostream>
using namespace std;

int main() {
   int x = 3, y, z;
   y = x++;
   z = ++x;
   cout << x << ", " << y << ", " << z;
   return 0;
}

Output

This would give us the output −

5, 3, 5

Why is this? Let's look at it in detail −

  • Initialize x to 3
  • Assign y the value we get by evaluating the expression x++, ie, the value of x before increment then increment x.
  • Increment x then assign z the value we get by evaluating the expression ++x, ie, value of x after the increment.
  • Print these values
raja
Published on 15-Feb-2018 12:25:42
Advertisements