Search code examples
cc99undefined-behaviorc89

Is negating INT_MIN undefined behaviour?


Let's say I have a variable i that comes from external sources:

int i = get_i();

Assuming i is INT_MIN and two's complement representation, is -i undefined?


Solution

  • It depends on the platform. C supports three representations for negative numbers (see section 6.2.6.2 of the C99 standard):

    • Two's complement.
    • One's complement.
    • Sign and magnitude.

    With one's complement and sign and magnitude, -INT_MIN is defined (and equal to INT_MAX). With two's complement, it depends on whether the value with sign bit 1 and all value bits zero is a trap representation or a normal value. If it's a normal value, -INT_MIN overflows, resulting in undefined behavior (see section 6.5 of the C99 standard). If it's a trap representation, -INT_MIN equals INT_MAX.

    That said, most modern platforms use two's complement without trap representations, so -INT_MIN typically results in undefined behavior.