mirror of
https://github.com/boostorg/safe_numerics.git
synced 2026-02-24 16:22:27 +00:00
corrections adjustments motivated by first real review of the library
This commit is contained in:
@@ -3,23 +3,22 @@
|
||||
#include <iostream>
|
||||
|
||||
#include "../include/safe_integer.hpp"
|
||||
//#include "../include/safe_compare.hpp"
|
||||
|
||||
void detected_msg(bool detected){
|
||||
std::cout << (detected ? "error detected!" : "error NOT detected! ") << std::endl;
|
||||
}
|
||||
|
||||
int main(int argc, const char * argv[]){
|
||||
// problem: undetected erroneous expression evaluation
|
||||
std::cout << "example 1:";
|
||||
std::cout << "undetected erroneous expression evaluation" << std::endl;
|
||||
std::cout << "Not using safe numerics" << std::endl;
|
||||
try{
|
||||
char x = 127;
|
||||
char y = 2;
|
||||
char z;
|
||||
signed char x = 127;
|
||||
signed char y = 2;
|
||||
signed char z;
|
||||
// this produces an invalid result !
|
||||
z = x + y;
|
||||
// it is the wrong result !!!
|
||||
assert(z != 129);
|
||||
// but assert fails to detect it since C++ implicitly
|
||||
// converts variables to int before evaluating he expression!
|
||||
@@ -28,18 +27,18 @@ int main(int argc, const char * argv[]){
|
||||
detected_msg(false);
|
||||
}
|
||||
catch(...){
|
||||
assert(false); // never arrive here
|
||||
assert(false); // we never arrive here
|
||||
}
|
||||
// solution: replace char with safe<char>
|
||||
std::cout << "Using safe numerics" << std::endl;
|
||||
try{
|
||||
using namespace boost::numeric;
|
||||
safe<char> x = 127;
|
||||
safe<char> y = 2;
|
||||
safe<char> z;
|
||||
// rather than producing and invalid result an exception is thrown
|
||||
safe<signed char> x = 127;
|
||||
safe<signed char> y = 2;
|
||||
safe<signed char> z;
|
||||
// rather than producing an invalid result an exception is thrown
|
||||
z = x + y;
|
||||
assert(false); // never arrive here
|
||||
assert(false); // we never arrive here
|
||||
}
|
||||
catch(std::range_error & e){
|
||||
// which can catch here
|
||||
|
||||
Reference in New Issue
Block a user