Subject: Re: Documentation of abs(3), div(3) etc.
To: None <tech-misc@netbsd.org>
From: Martijn van Buul <pino@dohd.org>
List: tech-misc
Date: 02/07/2007 12:37:44
* Christian Biere:
> the manpages for abs(3) and its variants define behavior for the "most
> negative integer" whereas the standard explicity states that the behavior is
> undefined if the result cannot be represented.

And your problem with this is? The standard claiming that it is undefined
means just that: the result is undefined, meaning that everything might
happen - including your program dumping core, and *including* leaving
it negative. The only problem is that the bug listed in BUGS is not a real
bug.

The problem arises from the fact that on a 2-compliment system (Which is
pretty much the entire world right now), the range of a signed int is
*slightly* asymettrical. On a 32 bits signal, the most positive signed
int is 217483647, while the most negative int is -217483648. So, if
your input is -217483648, the corresponding positive value is out of range.
You'd need to have a 33-bit signed int.

> This is a lie anyway because the code looks like
>
> 	return a < 0 ? -a : a;
>
> whereas it obviously means
>
> 	return a < 0 ? -(unsigned)a : a;

This is plain nonsense, on multiple grounds. First of all, you're casting
a signed int (known to be negative) to an unsiged int, which is pretty
broken to begin with, secondly, you're trying to negate the resulting
unsigned number, which isn't any better.

Consider -1: Assuming a 32 bit platform, your code would first cast the
signed -1 to an unsigned 0xffffffff. I wonder how you were planning to
turn it into - 0xffffffff, apart from secretly hoping that the compiler
will sneakily cast it back into an unsigned. But in that case, your 
modification is void.

> This would yield the documented behavior but of course it doesn't change the
> standard.

It would not. It would be silly.

-- 
Martijn van Buul - pino@dohd.org