C 2018 6.5 5 says:
If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.
When INT_MIN
is added to INT_MIN
, the result, two times INT_MIN
, is not in the range of values representable for its type, int
. So the behavior is undefined.
This means the C standard does not impose any requirements on what the implementation must do. It may act differently in different situations. It may produce an int
value of zero as a result. It may produce an int
value that is not zero as a result. It may trap. It may discard all of your program on the branch containing the undefined behavior. It may replace all of the code on that branch with other code.
The compiler may look at x+x
, which it can evaluate during compilation instead of during program execution, see that it has undefined behavior, and simply choose to replace it with whatever is “easiest” in some sense, such as zero. It can also look at !(x+x)
, see that it has undefined behavior, and make the same choice to replace it with zero.