Increment/Decrement

Hi, i would like to now why is the returned value 36 and not 37? Thanks for the answers :D
1
2
3
4
5
6
7
8
  int main ()
{
	int a = 14;
	int r = 10;

	r=(a++) + (--a) + r;
	cout<<r;
}
Last edited on
The value just so happens to be 36 due to the order your compiler decided to evaluate the line.
Line 6 of your program has undefined behavior. (which is bad)
The C++ standard does not dictate the order that functions are evaluated in a line of code, so you don't know what exactly will happen (operators ++ and -- count as functions, by the way).

Try running this code using cpp.sh (the picture of the gear next to your code) -- the printed value is different than the one your compiler calculated.

For more information, look at the section called "Undefined Behavior" in http://en.cppreference.com/w/cpp/language/eval_order
It probably explains it better than I can.

In general, don't mutate the same value more than once in the same line of code (in your case, you're changing the value of a twice).
Last edited on
Thanks
Topic archived. No new replies allowed.