example8.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 8:";
  10. std::cout << "undetected erroneous expression evaluation" << std::endl;
  11. std::cout << "Not using safe numerics" << std::endl;
  12. try{
  13. unsigned int x = 127;
  14. unsigned int y = 2;
  15. unsigned int z;
  16. // this produces an invalid result !
  17. z = y - x;
  18. std::cout << "error NOT detected!" << std::endl;
  19. std::cout << z << " != " << y << " - " << x << std::endl;
  20. }
  21. catch(const std::exception &){
  22. std::cout << "error detected!" << std::endl;
  23. }
  24. // solution: replace int with safe<int>
  25. std::cout << "Using safe numerics" << std::endl;
  26. try{
  27. using namespace boost::safe_numerics;
  28. safe<unsigned int> x = 127;
  29. safe<unsigned int> y = 2;
  30. safe<unsigned int> z;
  31. // rather than producing an invalid result an exception is thrown
  32. z = y - x;
  33. std::cout << "error NOT detected!" << std::endl;
  34. std::cout << z << " != " << y << " - " << x << std::endl;
  35. }
  36. catch(const std::exception & e){
  37. // which we can catch here
  38. std::cout << "error detected:" << e.what() << std::endl;
  39. }
  40. return 0;
  41. }