Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 598
SoniEx2 Avatar asked Dec 03 '22 14:12

SoniEx2


1 Answers

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.

like image 119
nwellnhof Avatar answered Dec 15 '22 15:12

nwellnhof