example20.cpp 845 B

1234567891011121314151617181920212223242526272829
  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. #include <iostream>
  7. #include <boost/safe_numerics/checked_result.hpp>
  8. #include <boost/safe_numerics/checked_result_operations.hpp>
  9. int main(){
  10. using ext_uint = boost::safe_numerics::checked_result<unsigned int>;
  11. const ext_uint x{4};
  12. const ext_uint y{3};
  13. // operation is a success!
  14. std::cout << "success! x - y = " << x - y;
  15. // subtraction would result in -1, and invalid result for an unsigned value
  16. std::cout << "problem: y - x = " << y - x;
  17. const ext_uint z = y - x;
  18. std::cout << "z = " << z;
  19. // sum of two negative overflows is a negative overflow.
  20. std::cout << "z + z" << z + z;
  21. return 0;
  22. }