How to check for a NAN (Not A Number) in C++ in embedded systems without exception handlers

Sometimes there are bugs or special corner conditions that makes a NAN (Not A Number) occur in code compiled from a C++ source and executed on an embedded systems without memory to run exception handlers.

Here is what @Jalf writes over at StackExchange:

According to the IEEE standard, NaN values have the odd property that comparisons involving them are always false. That is, for a float f, f != f will be true only if f is NaN.

Note that, as some comments below have pointed out, not all compilers respect this when optimizing code.

For any compiler which claims to use IEEE floating point, this trick should work.
Bookmark the permalink.

Leave a Reply

Your email address will not be published.