example14.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. #include <stdexcept>
  2. #include <iostream>
  3. #include <boost/safe_numerics/safe_integer.hpp>
  4. int main(int, const char *[]){
  5. // problem: cannot recover from arithmetic errors
  6. std::cout << "example 8: ";
  7. std::cout << "cannot detect compile time arithmetic errors" << std::endl;
  8. std::cout << "Not using safe numerics" << std::endl;
  9. try{
  10. const int x = 1;
  11. const int y = 0;
  12. // will emit warning at compile time
  13. // will leave an invalid result at runtime.
  14. std::cout << x / y; // will display "0"!
  15. std::cout << "error NOT detected!" << std::endl;
  16. }
  17. catch(const std::exception &){
  18. std::cout << "error detected!" << std::endl;
  19. }
  20. // solution: replace int with safe<int>
  21. std::cout << "Using safe numerics" << std::endl;
  22. try{
  23. using namespace boost::safe_numerics;
  24. const safe<int> x = 1;
  25. const safe<int> y = 0;
  26. // constexpr const safe<int> z = x / y; // note constexpr here!
  27. std::cout << x / y; // error would be detected at runtime
  28. std::cout << " error NOT detected!" << std::endl;
  29. }
  30. catch(const std::exception & e){
  31. std::cout << "error detected:" << e.what() << std::endl;
  32. }
  33. return 0;
  34. }