hhow to detect overflow in integer calculation

Discussion in 'C++' started by John Black, Apr 15, 2004.

  1. John Black

    John Black Guest

    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.
    John Black, Apr 15, 2004
    #1
    1. Advertising

  2. "John Black" <> wrote in message
    news:...
    > 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
    John Harrison, Apr 15, 2004
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Liza
    Replies:
    1
    Views:
    942
    Andy Dingley
    Jul 4, 2003
  2. Replies:
    3
    Views:
    333
    Alf P. Steinbach
    Mar 4, 2006
  3. Replies:
    3
    Views:
    310
    Robert Mabee
    Mar 21, 2006
  4. Jorgen Grahn
    Replies:
    5
    Views:
    1,194
    Andrew Poelstra
    Mar 15, 2010
  5. Detect if overflow required

    , Aug 14, 2007, in forum: Javascript
    Replies:
    10
    Views:
    253
    Evertjan.
    Aug 17, 2007
Loading...

Share This Page