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 1:"; 13 std::cout << "undetected erroneous expression evaluation" << std::endl; 14 std::cout << "Not using safe numerics" << std::endl; 15 try{ 16 std::int8_t x = 127; 17 std::int8_t y = 2; 18 std::int8_t z; 19 // this produces an invalid result ! 20 z = x + y; 21 std::cout << "error NOT detected!" << std::endl; 22 std::cout << (int)z << " != " << (int)x << " + " << (int)y << std::endl; 23 } 24 catch(const std::exception &){ 25 std::cout << "error detected!" << std::endl; 26 } 27 // solution: replace int with safe<int> 28 std::cout << "Using safe numerics" << std::endl; 29 try{ 30 using namespace boost::safe_numerics; 31 safe<std::int8_t> x = INT_MAX; 32 safe<std::int8_t> y = 2; 33 safe<std::int8_t> z; 34 // rather than producing an invalid result an exception is thrown 35 z = x + y; 36 } 37 catch(const std::exception & e){ 38 // which we can catch here 39 std::cout << "error detected:" << e.what() << std::endl; 40 } 41 return 0; 42 } 43