I'm adding really big numbers (a lot of them). I'm supposed to detect overflow errors. I did it years ago in Assembly by checking bits, but I've never done it in C++.

``````long long a = pow (2, 62.0);
long long b = pow (2, 62.0);
a += b;  // overflow - how do I detect this?``````

I know I can create a temp variable, set it equal to a + b, then if a and b are positive and the temp variable is negative, then overflow has occurred. But is there a way to check those bits instead?

Nice question.
3
Contributors
7
Replies
9
Views
8 Years
Discussion Span
Last Post by Dave Sinkula

Particularly check the first post. It talks about using MSB to detect
overflow.

So...?

``````if ( a > LONG_LONG_MAX - b )
{
puts("overflow");
}
else
{
a += b;
}``````
I got 1/4 of it.

I saw that snippet on your snippets section on Daniweb, Dave. It seemed along the lines of checking both addends to see if they're positive, then checking the sum to see if it's negative. So have all of the other examples I've seen. They all involve writing a function. I'll do that if I need to, and it looks like I do need to, but I was hoping to just check a bit/flag. All the resources I've seen suggest that isn't possible, so I wanted to confirm. Thanks.

I saw that snippet on your snippets section on Daniweb, Dave.

Hm. I didn't know it was there. :P

Hmm, that must be a coincidence :P

So...?

``````if ( a > LONG_LONG_MAX - b )
{
puts("overflow");
}
else
{
a += b;
}``````

Didn't notice your edit earlier. That ain't bad. I'll use it. But there's no way to do it by just checking a bit, right?

Hm. I didn't know it was there. :P

Yep.

Didn't notice your edit earlier. That ain't bad. I'll use it. But there's no way to do it by just checking a bit, right?

I don't believe there's anything I'd trust. If overflow is UB, I wouldn't want to rely on it for later verification.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.