Drew
Drew

Reputation: 13408

Does the C standard make an guarantees about the relationship between INT_MIN and INT_MAX?

For example, in both 2's and 1's complement, INT_MAX*-1 is a valid number. Is this guaranteed? Are there any other guarantees? Could INT_MIN be -1 or 0 on any architecture, for example? Is there anything we can know about (INT_MAX + INT_MIN)? Can we even know that (INT_MAX + INT_MIN) doesn't cause undefined behaviour?

Upvotes: 6

Views: 240

Answers (3)

Pascal Cuoq
Pascal Cuoq

Reputation: 80325

INT_MAX + INT_MIN is always defined because adding two numbers of opposite sign can never overflow.

To answer your question as precisely as possible, the C standard mandates either 2's complement, 1's complement or sign-magnitude representation. (C11 6.2.6.2:2). The int type may have padding bits, but the sign and value bits are in any case used to represent either symmetrical or almost-symmetrical sets of numbers. One always has INT_MIN == - INT_MAX - 1 or INT_MIN == - INT_MAX depending on whether the platform uses 2's complement.

And of course INT_MAX is at least 32767, corresponding to a minimum of 16 bits for value and sign bits.

Upvotes: 4

this
this

Reputation: 5290

You are guaranteed that INT_MIN is at most -32767 and INT_MAX at least 32767.

So INT_MAX-1 is always a valid int.

INT_MAX + INT_MIN is then also always defined.

Upvotes: 1

Scott Lawrence
Scott Lawrence

Reputation: 1073

The C specification requires INT_MIN to be -32767 or less, and INT_MAX to be 32767 or more. As nearly as I can tell, no further guarantees are made. Page 22: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf

Upvotes: 2

Related Questions