Here are two functions written in C that calculate the value of 1 / 0 and the assembly they produce in clang with -O1:
int example_1() {
return 1 / 0;
}
int example_2(int flag) {
return flag ? 1 / 0 : 5;
}
example_1:
ret
example_2:
mov eax, 5
ret
By inspecting the assembly, we can see that example_1 simply returns without setting the output register, meaning the function will return whatever happens to be in the eax register. example_2 always returns 5 no matter if the flag is set or not.
So example_2 would tell you that 1 / 0 == 5 and example_1 would tell you it's whatever happens to be in the register (likely zero).
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
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
"The language uses quiet-wraparound two's-complement arithmetic and is only suitable for use on platforms that support it", to
"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
"Everyone knows the language uses quiet-wraparound arithmetic on two's-complement platforms, so there's no need to expressly say that", to
"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.
6
u/pi_stuff Mar 23 '26
Why not test it?
3
u/Aaron1924 Mar 23 '26
INT_MIN/-1is just-INT_MIN, which is not representable under two's compliment, so depending on the language, this will either overflow, saturate toINT_MAX, throw an error, or give you UB1
u/LostInChrome Mar 23 '26
Depends on the language? problably either error, int max, int max + 1, or 0.