1 // Copyright (c) 2018Robert 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()11int main(){ 12 std::cout << "example 4: "; 13 std::cout << "implicit conversions change data values" << std::endl; 14 std::cout << "Not using safe numerics" << std::endl; 15 16 // problem: implicit conversions change data values 17 try{ 18 signed int a{-1}; 19 unsigned int b{1}; 20 std::cout << "a is " << a << " b is " << b << '\n'; 21 if(a < b){ 22 std::cout << "a is less than b\n"; 23 } 24 else{ 25 std::cout << "b is less than a\n"; 26 } 27 std::cout << "error NOT detected!" << std::endl; 28 } 29 catch(const std::exception &){ 30 // never arrive here - just produce the wrong answer! 31 std::cout << "error detected!" << std::endl; 32 return 1; 33 } 34 35 // solution: replace int with safe<int> and unsigned int with safe<unsigned int> 36 std::cout << "Using safe numerics" << std::endl; 37 try{ 38 using namespace boost::safe_numerics; 39 safe<signed int> a{-1}; 40 safe<unsigned int> b{1}; 41 std::cout << "a is " << a << " b is " << b << '\n'; 42 if(a < b){ 43 std::cout << "a is less than b\n"; 44 } 45 else{ 46 std::cout << "b is less than a\n"; 47 } 48 std::cout << "error NOT detected!" << std::endl; 49 return 1; 50 } 51 catch(const std::exception & e){ 52 // never arrive here - just produce the correct answer! 53 std::cout << e.what() << std::endl; 54 std::cout << "error detected!" << std::endl; 55 } 56 return 0; 57 } 58