![]() |
Home | Libraries | People | FAQ | More |
When some operation results in a result which exceeds the capacity of a data variable to hold it, the result is undefined. This is called "overflow". Since word size can differ between machines, code which produces correct results in one set of circumstances may fail when re-compiled on a machine with different hardware. When this occurs, Most C++ compilers will continue to execute with no indication that the results are wrong. It is the programmer's responsabiity to ensure such undefined behavior is avoided.
This program demonstrates this problem. The solution is to replace
instances of char type with safe<char>
type.
void example1(){
// problem: undetected erroneous expression evaluation
try{
char x = 127;
char y = 2;
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!
assert(z != x + y);
std::cout << static_cast<int>(z) << " != " << x + y;
detected_msg(false);
}
catch(...){
assert(false); // never arrive here
}
// solution: replace char with safe<char>
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
z = x + y;
assert(false); // never arrive here
}
catch(std::range_error & e){
// which can catch here
std::cout << e.what();
detected_msg(true);
}
}