"John Black" <bl***@eed.com> wrote in message
news:40***************@eed.com...
Hi,
If I have many integer calculation in my code, what's the best way to
detect integer overflow?
unsigned int i1 = 0xFFFFFF00, i2 = 0xFFFF;
then in statement unsigned int i3 = i1 + i2; there is overflow and
the result is not what I want. If such sum calculation scatters around
my code, I wonder what's the best way to catch it?
how about
if (std::numeric_limits<unsigned int>::max() - i1 < i2)
cout << "overflow";
#include <limits> to get std::numeric_limits.
And of course put all this in a function, or better still define a class
which overloads all the arithmetic operators and does the overflow checking
for you.
class SafeUInt
{
public:
SafeUInt(unsigned int v) : val(v) {}
...
private:
unsigned int val;
};
SafeUInt operator+(const SafeUInt& x, const SafeUInt& y)
{
// overflow detection here
...
}
john