fork download
  1. #include <iostream>
  2. #include <type_traits>
  3. #include <limits>
  4. using namespace std;
  5.  
  6. template <class integral_type>
  7. typename std::enable_if<std::is_integral<integral_type>::value, integral_type>::type NoOverflowMult(const integral_type a, const integral_type b)
  8. {
  9. if (!a || !b)
  10. return integral_type();
  11.  
  12. integral_type bound = ((a < 0) != (b < 0) ? std::numeric_limits<integral_type>::min() : std::numeric_limits<integral_type>::max());
  13.  
  14. if (std::abs(bound / a) < std::abs(b))
  15. return bound;
  16. return a*b;
  17. }
  18.  
  19. int main()
  20. {
  21. std::cout << "int" << std::endl;
  22. int ai = 2147483600;
  23. int bi = -1234;
  24. std::cout << ai << " * " << bi << " = " << NoOverflowMult(ai,bi) << std::endl;
  25. ai = std::numeric_limits<int>::min ();
  26. bi = 2;
  27. std::cout << ai << " * " << bi << " = " << NoOverflowMult(ai,bi) << std::endl;
  28.  
  29. std::cout << "unsigned short" << std::endl;
  30.  
  31. unsigned short aus = 65000;
  32. unsigned short bus = 2;
  33. std::cout << aus << " * " << bus << " = " << NoOverflowMult(aus,bus) << std::endl;
  34. aus = std::numeric_limits<unsigned short>::max();
  35. bus = std::numeric_limits<unsigned short>::min();
  36. std::cout << aus << " * " << bus << " = " << NoOverflowMult(aus,bus) << std::endl;
  37. return 0;
  38. }
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
int
2147483600 * -1234 = -2147483648
-2147483648 * 2 = -2147483648
unsigned short
65000 * 2 = 65535
65535 * 0 = 0