2

I'm making a small program solving basic math operations (*, /, +, -) and I'm using long long int (64-bit number) so I can do math operations with big numbers.

But there is a problem. I can check the operands if they are not over or under limit (using LONG_LONG_MAX and LONG_LONG_MIN). But when I (for example) multiply two very big numbers (which cause overflow of long long int) the LONG_LONG_MAX check doesn't work. Rather, the result is for -4.

Is there any chance in C/C++ check that? For example some try catch construction?

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
John
  • 67
  • 10
  • 4
    You can catch this by checking whether (for example) `b > MAX / a`. – Oliver Charlesworth Apr 08 '17 at 10:17
  • Yea I wanted to do something like this but I wondered If there is a "better" way. – John Apr 08 '17 at 10:28
  • `long long` is at least 64 bits, but it could be more. If you want a 64 bit varibale use `int64_t`. – 12431234123412341234123 Apr 08 '17 at 11:13
  • 1
    i do not see your problem, can you post a code example and values which do not work with it? – 12431234123412341234123 Apr 08 '17 at 11:15
  • You could always just use a big int library and not worry about it. – John Coleman Apr 08 '17 at 12:47
  • By the way, in C and C++ *signed* overflow is undefined behavior, so the fact that you get `-4` in your example isn't guaranteed by the standards. See this: http://stackoverflow.com/q/16188263/4996248 – John Coleman Apr 08 '17 at 12:55
  • take a look at this: [Building a logarithm function in C without using float type](http://stackoverflow.com/a/42108287/2521214) and study `DWORD fx32_mul(DWORD x,DWORD y)` the non asm version ... btw if you count the number of bits of mutiplication operands the result will be bounded by their sum.... so if under `64` you should be fine .... `64` is out of limit as you use signed version ... – Spektre Apr 09 '17 at 06:39

1 Answers1

2

For x = a*b;

if (a != 0 && x / a != b) {
// overflow handling
}

refer to this post for more details

multiplication of large numbers, how to catch overflow

Community
  • 1
  • 1
Himanshu
  • 36
  • 3