• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <stdexcept>
2 #include <iostream>
3 
4 #include <boost/safe_numerics/safe_integer.hpp>
5 
main(int,const char * [])6 int main(int, const char *[]){
7     // problem: cannot recover from arithmetic errors
8     std::cout << "example 8: ";
9     std::cout << "cannot detect compile time arithmetic errors" << std::endl;
10     std::cout << "Not using safe numerics" << std::endl;
11 
12     try{
13         const int x = 1;
14         const int y = 0;
15         // will emit warning at compile time
16         // will leave an invalid result at runtime.
17         std::cout << x / y; // will display "0"!
18         std::cout << "error NOT detected!" << std::endl;
19     }
20     catch(const std::exception &){
21         std::cout << "error detected!" << std::endl;
22     }
23     // solution: replace int with safe<int>
24     std::cout << "Using safe numerics" << std::endl;
25     try{
26         using namespace boost::safe_numerics;
27         const safe<int> x = 1;
28         const safe<int> y = 0;
29         // constexpr const safe<int> z = x / y; // note constexpr here!
30         std::cout << x / y; // error would be detected at runtime
31         std::cout << " error NOT detected!" << std::endl;
32     }
33     catch(const std::exception & e){
34         std::cout << "error detected:" << e.what() << std::endl;
35     }
36     return 0;
37 }
38