example4.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright (c) 2018Robert 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(){
  9. std::cout << "example 4: ";
  10. std::cout << "implicit conversions change data values" << std::endl;
  11. std::cout << "Not using safe numerics" << std::endl;
  12. // problem: implicit conversions change data values
  13. try{
  14. signed int a{-1};
  15. unsigned int b{1};
  16. std::cout << "a is " << a << " b is " << b << '\n';
  17. if(a < b){
  18. std::cout << "a is less than b\n";
  19. }
  20. else{
  21. std::cout << "b is less than a\n";
  22. }
  23. std::cout << "error NOT detected!" << std::endl;
  24. }
  25. catch(const std::exception &){
  26. // never arrive here - just produce the wrong answer!
  27. std::cout << "error detected!" << std::endl;
  28. return 1;
  29. }
  30. // solution: replace int with safe<int> and unsigned int with safe<unsigned int>
  31. std::cout << "Using safe numerics" << std::endl;
  32. try{
  33. using namespace boost::safe_numerics;
  34. safe<signed int> a{-1};
  35. safe<unsigned int> b{1};
  36. std::cout << "a is " << a << " b is " << b << '\n';
  37. if(a < b){
  38. std::cout << "a is less than b\n";
  39. }
  40. else{
  41. std::cout << "b is less than a\n";
  42. }
  43. std::cout << "error NOT detected!" << std::endl;
  44. return 1;
  45. }
  46. catch(const std::exception & e){
  47. // never arrive here - just produce the correct answer!
  48. std::cout << e.what() << std::endl;
  49. std::cout << "error detected!" << std::endl;
  50. }
  51. return 0;
  52. }