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