4.3 Floating point conversions

4.3.1 Do not convert an expression of wider floating point type to a narrower floating point type

The C++ Standard defines 3 floating point types: float, double, long double that, at least conceptually, increase in precision. Expressions that implicitly or explicitly cause a conversion from long double type to float or double, and from double to float should be avoided as they may result in data loss. When using a literal in a context that requires type float, use the F suffix, and for consistency use the L suffix in a long double context.

void foo ()
{
float f (1.0);        // @@- Non-Compliant -@@
f = 1.0F;             // @@+ Compliant +@@
                  
double d (1.0L);      // @@- Non-Compliant -@@
d = 1.0;              // @@+ Compliant +@@
                  
long double ld (1.0); // @@+ Compliant, but not good practice +@@
ld = 1.0L;            // @@+ Compliant +@@
                  
f = ld;               // @@- Non-Compliant -@@
d = ld;               // @@- Non-Compliant -@@
f = d;                // @@- Non-Compliant -@@
                  
d = f;                // @@+ Compliant +@@
ld = f;               // @@+ Compliant +@@
ld = d;               // @@+ Compliant +@@
}

References

  • HIC++ v3.3 – 6.2
  • HIC++ v3.3 – 10.14

Click here for references