example11.cpp 1.4 KB

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