Signed integer overflow undefined behavior or not?

John Colvin via Digitalmars-d digitalmars-d at puremagic.com
Fri Nov 13 01:33:48 PST 2015


On Friday, 13 November 2015 at 09:09:33 UTC, Don wrote:
> At the very least, we should change the terminology on that 
> page. The word "overflow" should not be used when referring to 
> both signed and unsigned types. On that page, it is describing 
> two very different phenomena, and gives the impression that it 
> was written by somebody who does not understand what they are 
> talking about.
> The usage of the word "wraps" is sloppy.
>
> That page should state something like:
> For any unsigned integral type T, all arithmetic is performed 
> modulo (T.max + 1).
> Thus, for example, uint.max + 1 == 0.
> There is no reason to mention the highly misleading word 
> "overflow".
>
> For a signed integral type T, T.max + 1 is not representable in 
> type T.
> Then, we have a choice of either declaring it to be an error, 
> as C does; or stating that the low bits of the 
> infinitely-precise result will be interpreted as a two's 
> complement value. For example, T.max + 1 will be negative.
>
> (Note that unlike the unsigned case, there is no simple 
> explanation of what happens).
>
> Please let's be precise about this.

I don't understand what you think is so complicated about it?

It's just circular boundary conditions. Unsigned has the 
boundaries at 0 and 2^n - 1, signed has them at -2^(n-1) and 
2^(n-1) - 1.

Less straightforwardly, but if you like modular arithmetic:
After arithmetic operations f is applied
unsigned: f(v) = v mod 2^n - 1
signed: f(v) = ((v + 2^(n-1)) mod (2^n - 1)) - 2^(n-1)


More information about the Digitalmars-d mailing list