Barr Group FacebookBarr Group TwitterBarr Group LinkedInBarr Group Vimeo

Rules

The following C coding rules relate to use of floating point arithmetic and variables in embedded software:

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

Rule 5.4.b.) When floating point calculations are necessary:

  1. Use the [C99] type names float32_t, float64_t, and float128_t.
  2. Append an f to all single-precision constants (e.g., pi = 3.1415927f;)
  3. If your math depends on it, ensure that the compiler supports double-precision (e.g., as demonstrated in the example below).
  4. Never test for equality or inequality of floating point values.

Example

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

Reasoning

There are a large number of risks of errors stemming from incorrect use of floating point arithmetic; these are outside the scope of this document. ([Seacord] has a nice explanation of these issues--as well as some suggested guidelines in his Chapter 6.) 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 floating point 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.

Exceptions

None.

Enforcement

These rules shall be enforced during code reviews.

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

Sign up for our newsletter today!

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.