• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 * [])11 int 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     // problem: arithmetic operations can yield incorrect results.
16     try{
17         std::int8_t x = 127;
18         std::int8_t y = 2;
19         std::int8_t z;
20         // this produces an invalid result !
21         z = x + y;
22         std::cout << z << " != " << x + y << std::endl;
23         std::cout << "error NOT detected!" << std::endl;
24     }
25     catch(const std::exception &){
26         std::cout << "error detected!" << std::endl;
27     }
28     // solution: replace std::int8_t with safe<std::int8_t>
29     std::cout << "Using safe numerics" << std::endl;
30     try{
31         using namespace boost::safe_numerics;
32         safe<std::int8_t> x = 127;
33         safe<std::int8_t> y = 2;
34         // rather than producing and invalid result an exception is thrown
35         safe<std::int8_t> z = x + y;
36     }
37     catch(const std::exception & e){
38         // which can catch here
39         std::cout << e.what() << std::endl;
40     }
41     return 0;
42 }
43