]>
git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/safe_numerics/example/example3.cpp
1 // Copyright (c) 2018 Robert Ramey
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)
9 #include <boost/safe_numerics/safe_integer.hpp>
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
18 // the following silently produces an incorrect result
20 std::cout
<< x
<< " != " << -1 << std::endl
;
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!
27 std::cout
<< "error NOT detected!" << std::endl
;
29 catch(const std::exception
&){
31 std::cout
<< "error detected!" << std::endl
;
33 // solution: replace unsigned int with safe<unsigned int>
34 std::cout
<< "Using safe numerics" << std::endl
;
36 using namespace boost::safe_numerics
;
37 safe
<unsigned int> x
= 0;
38 // decrement unsigned to less than zero throws exception
40 assert(false); // never arrive here
42 catch(const std::exception
& e
){
43 std::cout
<< e
.what() << std::endl
;
44 std::cout
<< "error detected!" << std::endl
;