Detect IEEE-754 floating point representation at compile time

Viewed 282

I'm looking for a way to detect whether a C compiler uses the IEEE-754 floating point representation at compile time, preferably in the preprocessor, but a constant expression is fine too.

Note that the __STDC_IEC_559__ macro does not fit this purpose, as an implementation may use the correct representation while not fully supporting Annex F.

2 Answers

Not an absolute 100% solution, but will get you practically close.

Check if the characteristics of floating type double match binary64:

#include <float.h>

#define BINARY64_LIKE ( \
  (FLT_RADIX == 2) \
  (DBL_MANT_DIG == 53)  \
  (DBL_DECIMAL_DIG == 17) \
  (DBL_DIG == 15) \
  (DBL_MIN_EXP == -1021) \
  (DBL_HAS_SUBNORM == 1) \
  (DBL_MIN_10_EXP == -307) \
  (DBL_MAX_EXP == +1024) \
  (DBL_MAX_10_EXP == +308))

BINARY64_LIKE usable at compile time. Need additional work though for older compilers that do not define them all like: DBL_HAS_SUBNORM since C11.

Likewise for float.

Since C11, code could use _Static_assert() to detect some attributes.

_Static_assert(sizeof(double)*CHAR_BIT == 64, "double unexpected size");

See also Are there any commonly used floating point formats besides IEEE754?.

Last non-IEEE754 FP format I used was CCSI 5 years ago.


Caution: Unclear why OP wants this test. If code is doing some bit manipulations of a floating point, even with __STDC_IEC_559__ defined there remains at least one hole: The endian of floating point and integer may differ - uncommon - but out there.

Other potential holes: support of -0.0, NaN sign, encoding of infinity, signalling NaN, quiet NaN, NaN payload: the usual suspects.

As of July 2020, this would still be compiler specific... though C2x intends to change that with the __STDC_IEC_60559_BFP__ macro - see Annex F, section F.2.

It might be noted that:

  • The compiler usually doesn't choose the binary representation. The compiler usually follows the target system's architecture (the chipset instruction design for the CPU / GPU, etc').

  • The use of non-conforming binary representations for floating-point is pretty much a thing of the past. If you're using a modern (or even a moderately modern) system from the past 10 years, you are almost certainly using a conforming binary representation.

Related