]>
git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/safe_numerics/example/example11.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 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.
20 // this produces an invalid result !
22 std::cout
<< z
<< " != " << x
+ y
<< std::endl
;
23 std::cout
<< "error NOT detected!" << std::endl
;
25 catch(const std::exception
&){
26 std::cout
<< "error detected!" << std::endl
;
28 // solution: replace std::int8_t with safe<std::int8_t>
29 std::cout
<< "Using safe numerics" << std::endl
;
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
;
37 catch(const std::exception
& e
){
38 // which can catch here
39 std::cout
<< e
.what() << std::endl
;