4 ms·
Why is it allowed to eliminate the branch? In most architectures abs(INT_MIN) returns INT_MIN which is negative
by meonukk 2y ago
Why is it allowed to eliminate the branch? In most architectures abs(INT_MIN) returns INT_MIN which is negative
- plorkyeran 2y agoCalling abs(INT_MIN) on twos-complement machine is not allowed by the C standard. The behavior of abs() is undefined if the result would not fit in the return value.
- ryao 2y agoWhere does it say that? I thought this was a famous example from formal methods showing why something really simple could be wrong. It would be strange for the standard to say to ignore it. The behavior is also well defined in two’s complement. People just don’t like it.
- plorkyeran 2y agohttps://busybox.net/~landley/c99-draft.html#7.20.6.1 https://busybox.net/~landley/c99-draft.html#7.20.6.1 "The abs, labs, and llabs functions compute the absolute value of an integer j. If the result cannot be represented, the behavior is undefined. (242)" 242 The absolute value of the most negative number cannot be represented in two's complement.
- Sohcahtoa82 2y agoI didn't believe this so I looked it up, and yup. Because of 2's complement limitations, abs(INT_MIN) can't actually be represented and it ends up returning INT_MIN.
- UncleMeat 2y agoIt's possible that there is an edge case in the output bounds here. I'm just using it as an example. Replace it with "int x = foo() ? 1 : 2;" if you want.