Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > hhow to detect overflow in integer calculation

Reply
Thread Tools

hhow to detect overflow in integer calculation

 
 
John Black
Guest
Posts: n/a
 
      04-15-2004
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.


 
Reply With Quote
 
 
 
 
John Harrison
Guest
Posts: n/a
 
      04-15-2004

"John Black" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed)...
> 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


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: Detect overflow by reading ALU's carryout Jorgen Grahn C++ 5 03-15-2010 09:52 PM
Detect if overflow required retrodans@googlemail.com Javascript 10 08-17-2007 12:51 PM
How to ignore/catch unsigned int calculation overflow linq936@hotmail.com C++ 3 03-21-2006 07:23 PM
How slow the 64 bit integer calculation? linq936@hotmail.com C++ 3 03-04-2006 05:06 AM
hHow do i recognise a web service ?? Liza XML 1 07-04-2003 12:54 AM



Advertisments