Pre increment and post increment

Hoon picture Hoon · Sep 23, 2012 · Viewed 15.4k times · Source

I'm having trouble understanding how Post Increment (++), Pre Increment (--) and addition/subtraction work together in an example.

x++ means add 1 to the variable.

x-- means subtract 1 from the variable.

But I am confused with this example:

int x = 2, y = 3, z = 1;`

y++ + z-- + x++;

I assume this means 3(+1) + 1(-1) + 2(+1) Which means the result should be 7.

But when I compile it, I get 6. I don't understand.

int main() {
  int x=2, y=3, z=1;
  int result;

  result = y++ + z-- + x++;    //this returns 6

  cout << result << endl;
  return 0;
}

Answer

juanchopanza picture juanchopanza · Sep 23, 2012

Because the postfix operator++ returns the original value, before incrementing the variable. The prefix operator++ increments the varialbe and returns a reference to it. The behaviour can be easily illustrated with an example:

#include <iostream>

int main()
{
  int n = 1;
  std::cout << n++ << "\n"; // prints 1
  std::cout << n << "\n";   // prints 2

  int m = 10;
  std::cout << "\n";
  std::cout << ++m << "\n"; // prints 11 
  std::cout << m << "\n";   // prints 11
}