How would you do this EFFICIENTLY? By that I mean that, if it is done in a tight loop, it would execute fast. Simply checking against the same result done in long doesn't help - it's got the overhead of casting. Thank!
[Lambert Stein]: Simply checking against the same result done in long doesn't help - it's got the overhead of casting.
I think this attitude is impractical - anything you do here will be slower than a single unchecked addition or subtraction. You can't reject a possibility because you think it's slower than you'd like - you can only choose the best option you can come up with, whatever its speed. Don't reject an option unless you have a better one in mind.
Having said that, you may get faster results like this:
I have not tested this at all, however. I will be interested to hear if you find something faster. [ October 08, 2007: Message edited by: Jim Yingst ]
Ah, yes. I actually wrote a SafeMath class some years ago and worked through all these, testing carefully. But obviously I don't remember the results as well as I should. (And can't find the class on my computers; oh well.) That trick I used works well with multiplication and division, but not addition and subtraction. All, right, try this:
The condition can be written more compactly, but I've tried to arrange it for maximum efficiency. [ October 08, 2007: Message edited by: Jim Yingst ]
Joined: Oct 30, 2006
So apparently it can't be done any other way than mine, right? Sure, I guess the previous post will work, but I was trying to avoid 'if' statements. Thanks to all, though!
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: int Addition/Subtraction Overflow Detection