example3.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 3:";
  10. std::cout << "undetected underflow in data type" << std::endl;
  11. std::cout << "Not using safe numerics" << std::endl;
  12. // problem: decrement can yield incorrect result
  13. try{
  14. unsigned int x = 0;
  15. // the following silently produces an incorrect result
  16. --x;
  17. std::cout << x << " != " << -1 << std::endl;
  18. // when comparing int and unsigned int, C++ converts
  19. // the int to unsigned int so the following assertion
  20. // fails to detect the above error!
  21. assert(x == -1);
  22. std::cout << "error NOT detected!" << std::endl;
  23. }
  24. catch(const std::exception &){
  25. // never arrive here
  26. std::cout << "error detected!" << std::endl;
  27. }
  28. // solution: replace unsigned int with safe<unsigned int>
  29. std::cout << "Using safe numerics" << std::endl;
  30. try{
  31. using namespace boost::safe_numerics;
  32. safe<unsigned int> x = 0;
  33. // decrement unsigned to less than zero throws exception
  34. --x;
  35. assert(false); // never arrive here
  36. }
  37. catch(const std::exception & e){
  38. std::cout << e.what() << std::endl;
  39. std::cout << "error detected!" << std::endl;
  40. }
  41. return 0;
  42. }