Suppose we want to cast a double value x to an int:
double x;
...
int n = (int)x;
This is perfectly fine unless x happens to be outside the range of int. In that case we get undefined behavior (C17, 6.3.1.4-1):
When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.
Which is the correct portable check on x that will allow conversion of the widest possible range of values while ensuring no undefined behavior is invoked?
My quick guess would be the following, but I am not sure it is correct (hence the question):
if(x > ((double)INT_MIN)-1.0 && x < ((double)INT_MAX)+1.0)
{
int n = (int)x;
...
}
else
// Error: out of range