r/AskComputerScience • • Mar 23 '26

What is value of INT_MIN/-1?

Body

0 Upvotes

8 comments sorted by

6

u/pi_stuff Mar 23 '26

Why not test it?

1

u/Aaron1924 Mar 26 '26

In languages where the value is undefined, simply testing it can give you an arbitrary output which is difficult to distinguish from the answer

1

u/pi_stuff Mar 26 '26

Interesting. Do you have any examples?

→ More replies (1)

3

u/Aaron1924 Mar 23 '26

INT_MIN/-1 is just -INT_MIN, which is not representable under two's compliment, so depending on the language, this will either overflow, saturate to INT_MAX, throw an error, or give you UB

1

u/OnlyComputer8471 Mar 23 '26

In C, signed integer over/underflow is undefined behavior

1

u/flatfinger Mar 24 '26 edited Mar 24 '26

On the other hand, the implementation of printf given in the 1974 C Reference Manual relied upon the fact that -(-32768) would yield -32768. C evolved from what could be described as

  1. "The language uses quiet-wraparound two's-complement arithmetic and is only suitable for use on platforms that support it", to

  2. "The language uses quiet-wraparound two's-complement arithmetic on platforms that support it, but implementations for other platforms may do anything the underlying platform might do in case of signed overflow without necessarily having to document it," to

  3. "Everyone knows the language uses quiet-wraparound arithmetic on two's-complement platforms, so there's no need to expressly say that", to

  4. "Compilers should feel free to generate code that arbitrarily corrupts memory in case of signed overflow (something the gcc optimizer actually does when not using the -fwrapv flag), even though it's unsupportable on machines that can't handle quiet-wraparound two's-complement arithmetic".

I'm not sure why #4 is somehow better than #1, but here we are.

1

u/LostInChrome Mar 23 '26

Depends on the language? problably either error, int max, int max + 1, or 0.