pre-boost Home Libraries People FAQ More

PrevUpHomeNext

Problem:Implicit conversions change data values

A simple assign or arithment expression will generally convert all the terms to the same type. Sometimes this can silently change values. For example, when a signed data variable contains a negative type, assigning to a unsigned type will be permitted by any C/C++ compiler but will be treated as large unsigned value. Most modern compilers will emit a compile time warning when this conversion is performed. The user may then decide to change some data types or apply a static_cast. This is less than satisfactory for two reasons:

This solution is the same as the above, Just replace instances of the int with safe<int>.

void example2(){
    // problem: undetected overflow in data type
    try{
        int x = INT_MAX;
        // the following silently produces an incorrect result
        ++x;
        //std::cout << x << " != " << -1;
        detected_msg(false);
    }
    catch(...){
        assert(false); // never arrive here
    }
    // solution: replace int with safe<int>
    try{
        using namespace boost::numeric;
        safe<int> x = INT_MAX;
        // throws exception when result is past maximum possible 
        ++x;
        assert(false); // never arrive here
    }
    catch(std::range_error & e){
        std::cout << e.what();
        detected_msg(true);
    }
}

PrevUpHomeNext