osource's blog

By osource, history, 6 weeks 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

»
6 weeks 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

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