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 <iostream> 8 9 #include <boost/safe_numerics/safe_integer.hpp> 10 main(int,const char * [])11int main(int, const char *[]){ 12 std::cout << "example 2:"; 13 std::cout << "undetected overflow in data type" << std::endl; 14 // problem: undetected overflow 15 std::cout << "Not using safe numerics" << std::endl; 16 try{ 17 int x = INT_MAX; 18 // the following silently produces an incorrect result 19 ++x; 20 std::cout << x << " != " << INT_MAX << " + 1" << std::endl; 21 std::cout << "error NOT detected!" << std::endl; 22 } 23 catch(const std::exception &){ 24 std::cout << "error detected!" << std::endl; 25 } 26 // solution: replace int with safe<int> 27 std::cout << "Using safe numerics" << std::endl; 28 try{ 29 using namespace boost::safe_numerics; 30 safe<int> x = INT_MAX; 31 // throws exception when result is past maximum possible 32 ++x; 33 assert(false); // never arrive here 34 } 35 catch(const std::exception & e){ 36 std::cout << e.what() << std::endl; 37 std::cout << "error detected!" << std::endl; 38 } 39 return 0; 40 } 41