Portability of uint over/underflow behavior

Don nospam at nospam.com
Mon Jan 5 07:01:23 PST 2009


Nick Sabalausky wrote:
> "Don" <nospam at nospam.com> wrote in message 
> news:gjsnf2$26g4$1 at digitalmars.com...
>> bearophile wrote:
>>> Don:
>>>> The question was about incrementing uint, not int. Preventing wraparound 
>>>> on uints would break everything!
>>> If optional runtime overflow controls are added to integral values, then 
>>> they are performed on ubyte/ushort/uint/ulong/ucent too, because leaving 
>>> a hole in that safety net is very bad and useless.
>> But uints HAVE no overflow! In the case of an int, you are approximating a 
>> mathematical infinite-precision integer. An overflow means you went 
>> outside the available precision.
>> A uint is quite different.
>> uint arithmetic is perfectly standard modulo 2^32 arithmetic.
>> Don't be confused by the fact that many people use them as approximations 
>> to infinite-precision positive integers. That's _not_ what they are.
>>
> 
> A uint is an int with the domain of possible values shifted by +uint.max/2 
> (while retaining binary compatibility with the overlapping values, of 
> course). Modulo 2^32 arithmetic is just one possible use for them. For other
> uses, detecting overflow can be useful.

I suspect that in most of the cases you're thinking of, you actually 
want to detect when the result is greater than int.max, not when it 
exceeds uint.max?

What you're calling 'overflow' in unsigned operations is actually the 
carry flag. The CPU also an overflow flag which applies to signed 
operations. When it's set, it means the result was so big that the sign 
was corrupted. (eg int.max + int.max gives a negative result). An 
overflow is always an error, I think. (And if you were using (say) a 
sign-magnitude representation instead of 2-s complement, int.max+int.max 
would be a _different_ wrong number).
But a carry is not an error. It's expected, and indicates that a 
wraparound occured.

By the way, there are other forms of integer which _are_ supported in 
x86 hardware. Integers which saturate to a maximum value can be useful. 
  ie, (int.max + 1 == int.max)



More information about the Digitalmars-d mailing list