This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

int Addition/Subtraction Overflow Detection

 
Lambert Stein
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[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 ]
 
Rob Spoor
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Of course that does not work, since the check will cause an overflow too, therefore the check will pass.


Output:
-2
1

And you're not going to tell me that there was no overflow here
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Lambert Stein
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic