Is it always possible to convert int to float ?
Reasonable - yes. int will always be converted to the final float . The conversion may lose some precision for large int values.
However, for pedantry the odd compiler may have problems.
C allows an excessively wide int , not just 16, 32, or 64 bits, and a float can have a limit range of 137.
This is not the top range of int or INT_MAX , which should be troubling. This is the bottom end. INT_MIN , which often has a +1 larger value than INT_MAX .
A value of 124 bits int min can be around -1.06e37, so it exceeds the minimum float range.
With a common binary32 float int wound must be greater than 128 bits in order to cause an infinity float .
So, what test is needed to detect this rare situation?
Form an exact power limit of-2 and do thorough math to avoid overflow or inaccuracy.
#if -INT_MAX == INT_MIN // rare non 2 complement machine #define INT_MAX_P1_HALF (INT_MAX/2 + 1) _Static_assert(FLT_MAX/2 >= INT_MAX_P1_HALF, "non-2 comp.`int` range exceeds `float`"); #else _Static_assert(-FLT_MAX <= INT_MIN, "2 complement `int` range exceeds `float`"); #endif
source share