Signed integer overflow undefined behavior or not?

Ali Çehreli via Digitalmars-d digitalmars-d at puremagic.com
Thu Nov 12 16:43:46 PST 2015


I searched but I could not find a definitive answer. I am pretty sure 
this thread will turn into yet another about what it should be, but I 
need an answer soon before updating my book to be review by Russel 
Winder, who will not give it a good mark before I get this part right. :)

Quoting from the following link:

   http://dlang.org/expression.html#AddExpression

"If both operands are of integral types and an overflow or underflow 
occurs in the computation, wrapping will happen. That is, uint.max + 1 
== uint.min and uint.min - 1 == uint.max."

Since it does not say "unsigned integral type", one might think it 
includes signed integral types as well. However, the rest of that quote 
is about the "wrap" behaviour of unsigned types and the fact that it 
conveniently uses an unsigned type in the only example makes me think 
that the spec means unsigned types there.

So the question is, do we support twos complement only, hence signed 
overflow is defined as wrap, or do we consider it as undefined behaviour?

Ali

P.S. The quote above has a misconception, which I've become aware of 
just recently myself: Contrary to what it may convey, underflow is not 
"having a value less than .min". For integral types, that is still 
called overflow[1]. Underflow is for floating point types only and it 
means "smaller in magnitude (that is, closer to zero) than the smallest 
value representable as a normal floating point number"[2]. So, underflow 
would not take a floating point to -.infinity; rather, towards less than 
.min_normal.

[1] https://en.wikipedia.org/wiki/Arithmetic_overflow (Note "greater in 
magnitude" there; it covers negative values as well.)

[2] https://en.wikipedia.org/wiki/Arithmetic_underflow


More information about the Digitalmars-d mailing list