4.4 Floating-integral conversions

4.4.1 Do not convert floating values to integral types except through use of standard library functions

An implicit or explicit conversion from a floating to an integral type can result in data loss due to the significant difference in the respective range of values for each type. Additionally, floating point to integral type conversions are biased as the fractional part is simply truncated instead of being rounded to the nearest integral value. For this reason use of standard library functions: std::floor and std::ceil is recommended if a conversion to an integral type is necessary.

#include <cstdint>
#include <cmath>
void foo (double d)
int32_t i = d;            // @@- Non-Compliant, fraction is truncated -@@
i = d + 0.5;              // @@- Non-Compliant, number is rounded -@@
i = std::floor (d);       // @@+ Compliant, fraction is truncated +@@
i = std::floor (d + 0.5); // @@+ Compliant, number is rounded +@@

Note: A return value of std::floor and std::ceil is of floating type, and an implicit or explicit conversion of this value to an integral type is permitted.


  • HIC++ v3.3 – 7.6

Click here for references