Why is the exit 16?

Asked

Viewed 94 times

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 was 16, but the logic would not be 15, since 4+5+6=15.

Compiler displays 2 identical errors on line 7:

"Operation in 'y' can be indefinite"

  • Although already answered, if you still want the result to be 15 : ) Do: x = (++y) + (((y++) + (y++));

1 answer

4


That’s exactly what the compiler is saying, there is no way he can guarantee what will happen with this expression that generates side effects, there is nothing in the specification that requires the code to work in a certain way, that is undefined behavior. There is no guaranteed order of execution. When you change 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 know very well what you’re doing. Doing each separate operation results in 15.

This is explained in more details on Wikipedia.

Behold how the current version of GCC generates the code and note the order change in relation to what is expected.

Now see how Clang 5.0 generates and note that he acts as expected.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.