Is negating INT_MIN undefined behaviour?

前端 未结 3 590
别那么骄傲
别那么骄傲 2021-01-03 08:34

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

int i = get_i();

Assuming i is INT_MIN

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-03 09:14

    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.

提交回复
热议问题