example1.cpp 1.3 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. try{
  13. std::int8_t x = 127;
  14. std::int8_t y = 2;
  15. std::int8_t z;
  16. // this produces an invalid result !
  17. z = x + y;
  18. std::cout << "error NOT detected!" << std::endl;
  19. std::cout << (int)z << " != " << (int)x << " + " << (int)y << 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<std::int8_t> x = INT_MAX;
  29. safe<std::int8_t> y = 2;
  30. safe<std::int8_t> z;
  31. // rather than producing an invalid result an exception is thrown
  32. z = x + y;
  33. }
  34. catch(const std::exception & e){
  35. // which we can catch here
  36. std::cout << "error detected:" << e.what() << std::endl;
  37. }
  38. return 0;
  39. }