## VernonDozier 2,218

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?

commented: Nice question. +11

## firstPerson 761

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

## Dave Sinkula 2,398

So...?

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

## VernonDozier 2,218

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.

## Dave Sinkula 2,398

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

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

commented: Hmm, that must be a coincidence :P +19

## VernonDozier 2,218

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?

## VernonDozier 2,218

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

Yep.

## Dave Sinkula 2,398

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.