Is it always possible to convert an int
to a float
?
Reasonably - yes. An int
will always convert to a finite float
. The conversion may lose some precision for great int
values.
Yet for the pedantic, an odd compiler could have trouble.
C allows for excessively wide int
, not just 16, 32 or 64 bit ones and float
could have a limit range, as small as 1e37.
It is not the upper range of int
or INT_MAX
that should be of concern. It is the lower end. INT_MIN
which often has +1 greater magnitude than INT_MAX
.
A 124 bit int
min value could be about -1.06e37, so that does exceed the minimal float
range.
With the common binary32 float
, an int
would need to be more than 128 bits to cause a float
infinity.
So what test is needed to detect this rare situation?
Form an exact power-of-2 limit and perform careful math to avoid overflow or imprecision.
#if -INT_MAX == INT_MIN
// rare non 2's complement machine
#define INT_MAX_P1_HALF (INT_MAX/2 + 1)
_Static_assert(FLT_MAX/2 >= INT_MAX_P1_HALF, "non-2's comp.`int` range exceeds `float`");
#else
_Static_assert(-FLT_MAX <= INT_MIN, "2's complement `int` range exceeds `float`");
#endif