Barr Group TwitterBarr Group Vimeo

Rules:

5.4.a. Avoid the use of floating point constants and variables whenever possible. Fixed-point math may be an alternative.

5.4.b. When floating point calculations are necessary:

           i. Use the C99 type names float32_t, float64_t, and float128_t.

          ii. Append an ‘f’ to all single-precision constants (e.g., pi = 3.141592f).

         iii. Ensure that the compiler supports double precision, if your math depends on it.

         iv. Never test for equality or inequality of floating point values.    

          v. Always invoke the isfinite() macro to check that prior calculations have resulted in neither INFINITY nor NAN.

Example:

#include 
#if (DBL_DIG < 10)   // Ensure the compiler supports double precision.
#   error “Double precision is not available!”
#endif

Reasoning: A large number of risks of defects stem from incorrect use of floating point arithmetic.8  By default, C promotes all floating-point constants to double precision, which may be inefficient or unsupported on the target platform. However, many microcontrollers do not have any hardware support for floatingpoint math. The compiler may not warn of these incompatibilities, instead performing the requested numerical operations by linking in a large (typically a few kilobytes of code) and slow (numerous instruction cycles per operation) floating- point emulation library.

Enforcement: These rules shall be enforced during code reviews.


Footnotes

[8] [CERT-C] has an explanation of these issues in its Chapter 5.

 

What’s happening and how it’s done. Get in the know.

Sign Up for Our Newsletter

Receive free how-to articles, industry news, and the latest info on Barr Group webinars and training courses via email. 

To prevent automated spam submissions leave this field empty.