Updated: Fast(est?) portable simple solution outlined in Part 3
Continued in Part 2.
Updated: I see Linus Torvalds (of ye verily Linux fame) crying about the same problem way back when - did he ever find a better solution than the MS one?
I was checking out a new blog site that the Microsoft Vista Shell team has (a former friend of mine runs that group there), and, digging around, happened upon an old post from Raymond Chen (that guy is amazing - LOVE his blog)
This particular post was about integer overflow and resultant subtle problems. Its a trickier thing than most people think, and has all sorts of well documented long standing "famous" bugs.
That led me to Microsoft's very nice SafeInt class - but yowza - safe addition takes 3 compares and 3 branches? In the trivial case? (i.e. positive number plus a positive number)
I saw that there's been an update that deals with this by casting to int64, doing the add, and then two compares and 1 branch, and a cast into a int32, but yoinks... someone must have a better solution than that.
I'm going to do a little research - but someone? anyone? Faster/better solution?
(My timing tests show - I wrote a tiny benchmark - with the "safe int" exception throwing on, that simple addition takes twice as long (almost) - that really the state of the art?)