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?

Comments
Nice question.

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.

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 article has been dead for over six months. Start a new discussion instead.