Re: Documentation of abs(3), div(3) etc.
Alan Barrett <[email protected]>
| Newsgroups | gmane.os.netbsd.devel.general |
|---|---|
| Message-ID | <[email protected]> |
On Wed, 07 Feb 2007, Martijn van Buul wrote: > * 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. I'd like out man page to both document what we do, and document what parts of that are non-standard. At present, out abs(3) seems to accurately document what we do, but not that part of it is undefined by the standard. > > 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. The suggested replacement code is correct. Unsigned arithmetic in C is defined in terms of modular arithmetic in mathematics. The original code would invoke undefined behaviour if it appeared in user-written code. (The mathematical result of -a might be outside the range representable by a signed int, which gives undefined bahaviour.) Since the code in queation is part of the implementation, I think we don't need to worry about that. --apb (Alan Barrett)