• 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 3:";
13     std::cout << "undetected underflow in data type" << std::endl;
14     std::cout << "Not using safe numerics" << std::endl;
15     // problem: decrement can yield incorrect result
16     try{
17         unsigned int x = 0;
18         // the following silently produces an incorrect result
19         --x;
20         std::cout << x << " != " << -1 << std::endl;
21 
22         // when comparing int and unsigned int, C++ converts
23         // the int to unsigned int so the following assertion
24         // fails to detect the above error!
25         assert(x == -1);
26 
27         std::cout << "error NOT detected!" << std::endl;
28     }
29     catch(const std::exception &){
30         // never arrive here
31         std::cout << "error detected!" << std::endl;
32     }
33     // solution: replace unsigned int with safe<unsigned int>
34     std::cout << "Using safe numerics" << std::endl;
35     try{
36         using namespace boost::safe_numerics;
37         safe<unsigned int> x = 0;
38         // decrement unsigned to less than zero throws exception
39         --x;
40         assert(false); // never arrive here
41     }
42     catch(const std::exception & e){
43         std::cout << e.what() << std::endl;
44         std::cout << "error detected!" << std::endl;
45     }
46     return 0;
47 }
48