Why does the output give 16?

4
#include <iostream>

int main()
{
    int x, y = 3;
    x = (++y) + (++y) + (++y);
    std::cout << "y = " << y << std::endl;
    setlocale(LC_ALL, "");
    std::cout << "O valor de x é " << x << std::endl;
    std::cout << "y = " << y;
    return 0;
}

I ran this code and the output gave 16, but by logic would not be 15, since 4 + 5 + 6 = 15.

The compiler displays 2 equal errors in line 7:

  

"The operation on 'y' can be undefined"

    
asked by anonymous 31.01.2018 / 19:29

1 answer

4

This is exactly what the compiler is saying, there is no way to guarantee what will happen to this expression that generates side effects, there is nothing in the specification that forces the code to work in a certain way, that is undefined behavior . There is no guaranteed order of execution. When changing a variable more than once in the same expression, among other operations, it is difficult to define the correct result.

Essentially, never use assignment operators in complex operations like this, unless you are very well aware of what you are doing. If you do each separate operation it results in 15.

This is explained in more details on Wikipedia .

See how the current version of GCC generates code and notice the change in order compared to what is expected.

Now see how Clang 5.0 builds and note that it acts as expected.

Put in your browser and see how Clang actually generates the correct result of 15 (yes, you are running on your browser).

    
31.01.2018 / 20:08