1

I wrote the following C++ code to check for an underflow. Not sure this is a good practice or not.

#include <limits>
#include <iostream>

int main()
{
    float d = 1.e-29;
    std::cout<<"d: "<<d<<" underflow? "<<(d<std::numeric_limits<float>::min())<<std::endl;
    d = 1.e-59;
    std::cout<<"d: "<<d<<" underflow? "<<(d<std::numeric_limits<float>::min())<<std::endl;
}

The printouts are

d: 1e-29 underflow? 0
d: 0 underflow? 1
Hailiang Zhang
  • 17,604
  • 23
  • 71
  • 117

1 Answers1

3

You cannot check for underflow or overflow after a variable has been assigned a value by comparing it with the standard limits.

Simple example:

int v1 = INT_MAX;
int v2 = INT_MAX;
int v3 = v1 * v2;

The expression v1 * v2 results in an overflow. However the value of v3 will still be a valid int.

You have to performs checks prior to v1 * v2 to determine whether it will result in an overflow.

R Sahu
  • 204,454
  • 14
  • 159
  • 270