...
This solution replaces the float
with a double
. Furthermore, it uses a static assertion (see to guarantee that the double
type can represent any int
without loss of precision. (See guideline DCL03-C. Use a static assertion to test the value of a constant expression) to guarantee that the double
type can represent any int
without loss of precision..)
Code Block | ||
---|---|---|
| ||
#include <stdio.h> #include <float.h> /* define or include a definition of static_assert */ static_assert(sizeof(int) * 8 <= DBL_MANT_DIG); // 8 = bits / char int main() { int big = 1234567890; double approx = big; printf("%d\n", (big - (int)approx)); return 0; } |
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
Related Guidelines
This rule appears in the C++ Secure Coding Standard as : FLP36-CPP. Beware of precision loss when converting integral types to floating point.
This rule appears in the Java Secure Coding Standard as : INT03-J. Do not cast numeric types to wider floating-point types without range checking.
Bibliography
Wiki Markup |
---|
\[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] 6.3.1.4: "Real floating and integer" |
...