Can't understand how -INT_MIN transform to INT_MIN in bit level
-
Write out the binary and then do complement + 1. – stark Feb 11 '22 at 14:02
-
4Read about [two's complement](https://en.wikipedia.org/wiki/Two's_complement). The values are different in other [number representations](https://en.wikipedia.org/wiki/Signed_number_representations) – pmg Feb 11 '22 at 14:03
-
2`-INT_MIN` cannot be represented in an `int` (for two's complement). – Ian Abbott Feb 11 '22 at 14:08
-
2Most systems uses 2's complement which means that `-INT_MIN` is greater than `INT_MAX`, i.e. there will be integer overflow. In other words: The real result is `INT_MAX + 1` and that overflows to `INT_MIN`. Notice that the C standard doesn't specify that behavior – Support Ukraine Feb 11 '22 at 14:10
1 Answers
In common architecture negative values use 2's complement.
This has an immediate outcome: -INT_MIN will be greater (by 1) that INT_MAX. That means the the result value will be undefined(*). And still for common architectures it just happen to be -INT_MIN again.
Just look at what happens for signed bytes (values are lower so easier to handle) MIN is -128 and MAX is 127. In hexa, they are respectively 0x80 and 0x7F. But the representation of 128 as an int value is again 0x80. And when you assign that back to a signed byte type you end with (- (-128)) gives -128...
As char has a lower rank than int, the char is promoted to int, the operation gives a result that can be represented as an int and the conversion to a char gives an implementation defined result. But - INT_MIN is an expression that would give a result that cannot be represented as a int value. This is an exceptional condition and the behaviour is explicitely undefined per standard. That being said, common implementation handle everything the same...

- 143,923
- 11
- 122
- 252
-
6Re “the result value will be implementation defined”: The behavior of negating `INT_MIN` is not defined by the C standard, per C 2018 6.5 5: “If an *exceptional condition* occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.” – Eric Postpischil Feb 11 '22 at 14:31