Re: Unsigned integer overflow detection
Raymond wrote:
Source:
http://moryton.blogspot.com/2007/08/detecting-overflowunderflow-when.html
Example from source:
char unsigned augend (255);
char unsigned const addend (255);
char unsigned const sum (augend + addend);
if (sum < augend)
{
std::puts ("Overflowed!");
}
sum = augend + addend
sum = 255 + 255
sum = 510 modulo 256 // Behind the scenes.
sum = 254
Does it touch any implementation defined or undefined behaviour, or
was that specific to signed integers (on some platforms)?
No, the behaviour is well-defined. All arithmetic operations with
unsigned values work modulo 2^N, where N is the number of bits in
the representation of the number.
What other methods are there for detecting unsigned integer overflow
and/or underflow in C++?
If you look in the archives (use Google Groups interface, e.g.), you
should find that unsigned does not overflow. There is no such thing
as "underflow" AFA integers are concerned, IIUIC.
There is no way to "detect" it in the current language. There is only
a way to "predict" it:
unsigned a = UINT_MAX - 2, b = UINT_MAX - 3; // or whatever
if (UINT_MAX - a < b)
std::cout << "Adding " << a << " to " << b
<< " would \"overflow\"\n";
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask