]> git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/safe_numerics/example/example8.cpp
import new upstream nautilus stable release 14.2.8
[ceph.git] / ceph / src / boost / libs / safe_numerics / example / example8.cpp
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
11 int main(int, const char *[]){
12 std::cout << "example 8:";
13 std::cout << "undetected erroneous expression evaluation" << std::endl;
14 std::cout << "Not using safe numerics" << std::endl;
15 try{
16 unsigned int x = 127;
17 unsigned int y = 2;
18 unsigned int z;
19 // this produces an invalid result !
20 z = y - x;
21 std::cout << "error NOT detected!" << std::endl;
22 std::cout << z << " != " << y << " - " << x << std::endl;
23 }
24 catch(const std::exception &){
25 std::cout << "error detected!" << std::endl;
26 }
27 // solution: replace int with safe<int>
28 std::cout << "Using safe numerics" << std::endl;
29 try{
30 using namespace boost::safe_numerics;
31 safe<unsigned int> x = 127;
32 safe<unsigned int> y = 2;
33 safe<unsigned int> z;
34 // rather than producing an invalid result an exception is thrown
35 z = y - x;
36 std::cout << "error NOT detected!" << std::endl;
37 std::cout << z << " != " << y << " - " << x << std::endl;
38 }
39 catch(const std::exception & e){
40 // which we can catch here
41 std::cout << "error detected:" << e.what() << std::endl;
42 }
43 return 0;
44 }