Re: Coding tip for newbies
Roedy Green wrote:
> However, hardware would naturally return 0, and I would think 0 would
> be much less of a problem as a result that an unchanged negative
> result. Sun probably had to check specially for this case since
> hardware (though I can't say for the JVM byte code) would most
> naturally return 0.
The man page for abs on my system says this:
Trying to take the absolute value of the most negative integer is not
defined.
Using this C program:
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("%d\n", abs(INT_MIN));
return 0;
}
I got -2147483648.
Looking at the a.out via objdump -d, it seems that the abs(INT_MIN) was
optimized, so I ran another program to make it harder to optimize, to
find the actual instructions for abs() (the argument and return in eax,
obviously AT&T style, not Intel):
80483c7: 89 c2 mov %eax,%edx
80483c9: c1 fa 1f sar $0x1f,%edx
80483cc: 31 d0 xor %edx,%eax
80483ce: 29 d0 sub %edx,%eax
This is on an x86 system. I don't think "hardware would most naturally
return 0": it would most naturally return the "simpler" computation.
Returning 0 in an awfully special case would not be terribly simple.
Also, I think it would be reasonable to expect that this one special
case is in practice rather moot. If -2^31 were a viable input to a
program, then I would expect that -2^31 - 1 should also be viable, so
the range of a 32-bit signed integer becomes insufficient for the program.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth