clanguage-lawyerundefined-behaviorinteger-overflownegation

Why does exactly -LLONG_MIN lead to undefined behavior?


Why does exactly -LLONG_MIN lead to undefined behavior?

C11, 6.5.3.3p3:

The result of the unary - operator is the negative of its (promoted) operand. The integer promotions are performed on the operand, and the result has the promoted type.

Here we see that the C standard doesn't require that unary - operator to be implemented, for example, using bitwise-not followed by adding 1, where "adding 1" may lead to undefined behavior.

How to deduce from the quoted text that -LLONG_MIN leads to undefined behavior?


Solution

  • How to deduce from the quoted text that -LLONG_MIN leads to undefined behavior?

    It is not possible to deduce it from the quoted text. You also need this text https://port70.net/~nsz/c/c11/n1570.html#6.5p5 :

    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.

    On implementations in which the mathematical result of -LLONG_MIN is not representable in long long type, this rule is triggered and behavior is undefined.