Addition???

Why the equation like this:
(for x = 5)
int result = 2*x+(++x+3)*3
equals
37 ????
not
39 (2*5+(6+3)*3=39)
closed account (1vRz3TCk)
andrewbl wrote:
... int result = 2*x+(++x+3)*3 ...

because you are using code that exhibits undefined behavior.

When you or the compiler evaluated x when do you do it? When is the side-effect of the the increment put in place (the only guarantee is that it will be in place before the next sequence point).

Sorry there is a bug, my fault
2*5+(6+3)*3=37 it should be but it is 39
I have this on the software engineering classes. In java the result is 37. Why is the result different?
So it is in C++, some compilers will make the result 39, others 37. Anything is possible, nothing is guaranteed by the standard.
Using ++x inside a compound statement that uses other versions of 'x' is undefined (i.e. compiler-dependent) behaviour.

Imagine this function:
1
2
3
int add(int x, int y) { return x+y; }
int t = 8;
cout << add(++t, ++t);

The compiler has no way of knowing what you want. Do you want add(9, 10)? Do you want add(8, 8) and then set t = 10? The result will probably be 20 (add(10, 10)), but it might be different on some compilers;
I don't see the issue.. ++ is a pre-increment operator. It will increment x first, and then use the value in the entire statement. It has higher priority over other arithmetic operations. So when your statement is compiled, it has used x=6 in the operations. As simple as that...
Wow... That was truly enlightening.. Thank you! :)
Topic archived. No new replies allowed.