osource's blog

By osource, history, 3 years ago, In English

let's say I have 2 numbers x and y. How do I check if x*y results in an overflow in C++?. Both x and y are long long int.

  • Vote: I like it
  • +1
  • Vote: I do not like it

| Write comment?
»
3 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

if x>LLONG_MAX/y(or y>LLONG_MAX/x), then overflow

»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it
long long mul = a * b;
if (mul / a != b) {
  //overflowed
}