If you'll only be adding positive numbers and you can guarantee that all parameters passed to add() will be within integer range, a heuristic as simple as this will work:

sub add { use integer; my $result = $_[0] + $_[1]; return $result if $result < $_[0] or $result < $_[1]; goto &myadd; }

That technique can be extended if you need to handle negative overflow as well.

If you can't guarantee the integrity of your parameters, you'll need to know in advance the overflow point of the system you're on. This is something that you could potentially test for in your Makefile.PL. Once you know that, you can test each incoming parameter against the top and bottom, and then add them if they pass.

P.S. A few points about quidity's response above: I believe that due to the nature of arbitrary precision integer math, making these checks beforehand will be a speed win in most cases. Also, Math::BigInt is disgustingly slow; if you want to be embarassed, compare it to Python or Ruby's built-in bigints for speed. There is a Math::BigIntFast on the CPAN -- I haven't benchmarked it yet. You might take a look at that.

Another plus for Python and Ruby is that they automatically upgrade to bigints/bignums, while you have to explicitly load the BigInt library and do it by hand in Perl. This is something I'd very much like to see.

P.P.S. Nick Clark is working on some modifications that will make integer math in Perl be much more sensible (though I haven't yet heard any plans to involve bigints). If you're interested in this sort of thing, take a look here, for instance.

-dlc


In reply to Re: Detecting ineger overflow by dchetlin
in thread Detecting ineger overflow by TheHobbit

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.