-2

I am a complete beginner in programming and just started learning C++ about 2 days ago. There is a strange problem that i dont really understand.

int main()
{
   int value1;
   int value2;
   cin >> value1 >> value2;
   value1 = (value1 > 5) ? value1++ : value1;
   value2 = value2++;
   cout << value1 << " " << value2 << endl;
}

Well lets say value1 = 6 and value2 = 2. Well the display is 6 3. As far as i understand the post increment operator adds one to its operand but the value of the current expression that it is used in is still the "un-incremented" value, which makes sense for value2's case. value2 is assigned to the expression "value2++" and value2++ has value 2, once it is assigned the effects of the ++ takes place and adds 1 to the value of value2. But how about for value1's case? Why wansnt value1's value incremented after the post increment operator was used in the codes above?

Anthony
  • 409
  • 1
  • 5
  • 10
  • That looks like undefined behaviour. The same as saying `value1 = value1++`. See [this SO question](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) for more on that. – juanchopanza Nov 10 '13 at 11:42

1 Answers1

0

The error is that your assignment of value1 is effectively value = value1++;... so you want to read the current value of value1, 6, and then increment it but also store that 6 somewhere else (that overwrites where the incrementation occurred).

Use value1 = (value1 > 5) ? value1 + 1 : value1; instead.

mah
  • 39,056
  • 9
  • 76
  • 93