example2.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // Copyright (c) 2018 Robert Ramey
  2. //
  3. // Distributed under the Boost Software License, Version 1.0. (See
  4. // accompanying file LICENSE_1_0.txt or copy at
  5. // http://www.boost.org/LICENSE_1_0.txt)
  6. #include <iostream>
  7. #include <boost/safe_numerics/safe_integer.hpp>
  8. int main(int, const char *[]){
  9. std::cout << "example 2:";
  10. std::cout << "undetected overflow in data type" << std::endl;
  11. // problem: undetected overflow
  12. std::cout << "Not using safe numerics" << std::endl;
  13. try{
  14. int x = INT_MAX;
  15. // the following silently produces an incorrect result
  16. ++x;
  17. std::cout << x << " != " << INT_MAX << " + 1" << std::endl;
  18. std::cout << "error NOT detected!" << std::endl;
  19. }
  20. catch(const std::exception &){
  21. std::cout << "error detected!" << std::endl;
  22. }
  23. // solution: replace int with safe<int>
  24. std::cout << "Using safe numerics" << std::endl;
  25. try{
  26. using namespace boost::safe_numerics;
  27. safe<int> x = INT_MAX;
  28. // throws exception when result is past maximum possible
  29. ++x;
  30. assert(false); // never arrive here
  31. }
  32. catch(const std::exception & e){
  33. std::cout << e.what() << std::endl;
  34. std::cout << "error detected!" << std::endl;
  35. }
  36. return 0;
  37. }