example10.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #include <iostream>
  2. #include <cstdint>
  3. #include <boost/safe_numerics/safe_integer.hpp>
  4. using namespace std;
  5. using namespace boost::safe_numerics;
  6. void f(const unsigned int & x, const int8_t & y){
  7. cout << x * y << endl;
  8. }
  9. void safe_f(
  10. const safe<unsigned int> & x,
  11. const safe<int8_t> & y
  12. ){
  13. cout << x * y << endl;
  14. }
  15. int main(){
  16. cout << "example 4: ";
  17. cout << "mixing types produces surprising results" << endl;
  18. try {
  19. std::cout << "Not using safe numerics" << std::endl;
  20. // problem: mixing types produces surprising results.
  21. f(100, 100); // works as expected
  22. f(100, -100); // wrong result - unnoticed
  23. cout << "error NOT detected!" << endl;;
  24. }
  25. catch(const std::exception & e){
  26. // never arrive here
  27. cout << "error detected:" << e.what() << endl;;
  28. }
  29. try {
  30. // solution: use safe types
  31. std::cout << "Using safe numerics" << std::endl;
  32. safe_f(100, 100); // works as expected
  33. safe_f(100, -100); // throw error
  34. cout << "error NOT detected!" << endl;;
  35. }
  36. catch(const std::exception & e){
  37. cout << "error detected:" << e.what() << endl;;
  38. }
  39. return 0;
  40. }