Boost logo

Boost Users :

From: Zeljko Vrba (zvrba_at_[hidden])
Date: 2008-08-17 14:31:01


On Sun, Aug 17, 2008 at 07:43:14PM +0200, Andrea Denzler wrote:
>
> To get an assert on integer overflow at runtime you must write your own
> integer class, handling the conversion from all integral types (modern CPUs
> doesn't offer interrupts on integer overflow). You will have an overhead of
> course, but it can be minimized very well using assembler instructions.
>
That's what I proposed. I listed my requirements and asked whether such
a library already existed :-)

>
> The operators < and > works well mathematically. The problem with -1U < 2 is
> that you are going to have an overflow because you are converting -1 to
> unsigned. This happens before the operator is applied (it require both value
> of the same type).
>
Well, the first expression was a typo, it should be -1 < 2U. Technically, no
overflow happens because signed->unsigned conversion is well-defined (even for
negative numbers). I know _why_ it happens, I was complaining on the
definition which mathematically makes no sense.

==

It is ironic that the experts recommend to use signed integers, yet the
language definition is backwards since it is biased towards unsigned
arithmetic: in three of four possible mixes (s/u,u/s,u/u) the arithmetic is
unsigned, and only in the s/s case the arithmetic is signed and behaves
according to the usual mathematical definitions.

Given the language as it is, the advice should be to use unsigned most of the
time, because it is contagious and has always a defined behavior. So one
should actually only cast to a signed type only at the moment a signed
interpretation is needed. This works nice for 2nd complement which preserves
signedness even with unsigned operations (at least across add/sub), though it
would probably horribly break with 1st complement or sign-magnitude
representation. Blindly multiplying or dividing and reinterpreting the result
as signed will break (i.e. give incorrect result) even with 2nd complement
representation. <rant>~30 years since C has been invented, ~20 since C++ has
been invented, and they still have no sane integer arithmetic defined, not even
as an option *shrug*</rant> <sarcasm>I guess the best choice is to use float,
at least one knows what to expect.</sarcasm>


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net