C++ (increment and decrement) problem, Need help!

Please answer, why the value of this becomes 14? My answer is 13, what's yours and if your answer is 14, please explain why. Thank you!
1
2
3
4
5
6
7
8
9
   using namespace std;
    int main()
    {
        int x = 5, y = 5, z;
        x = ++x; y = --y;
        z = x + ++x;
        cout << z;
        return 0;
    }
Bottom line: the program results in undefined behavior at line 6, so my answer is "the program plays 'God Save The Queen' at 85 dB. My answer is just as valid as yours.

Line 5 increments x (to 6)then assigns it to itself. The next statement decrements y (to 4) then assigns it to itself. The assignments are redundant so line 5 is equivalent to ++x; --y; The result is x=6 and y=4.

Line 6 is undefined because you can't access a variable with a side effect more than once in an expression. The language doesn't specify whether the left side of "+" gets evaluated before, after, or simultaneously with the right side, and since the right side modifies the value of x, who knows what value the left side will see.
Topic archived. No new replies allowed.