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?

kvprajapati commented: Nice question. +11

Google is your friend.

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

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

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.