hhow to detect overflow in integer calculation

J

John Black

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?

Thanks.
 
J

John Harrison

John Black said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top