I have a numerical method that could return nan or inf if there was an error, and for testing purposed I’d like to temporarily force it to return nan or inf to ensure the situation is being handled correctly. Is there a reliable, compiler-independent way to create values of nan and inf in C?
After googling for about 10 minutes I’ve only been able to find compiler dependent solutions.
You can test if your implementation has it:
The existence of
INFINITYis guaranteed by C99 (or the latest draft at least), and “expands to a constant expression of type float representing positive or unsignedinfinity, if available; else to a positive constant of type float that overflows at translation time.”
NANmay or may not be defined, and “is defined if and only if the implementation supports quiet NaNs for the float type. It expands to a constant expression of type float representing a quiet NaN.”Note that if you’re comparing floating point values, and do:
even then,
is false. One way to check for NaN would be:
You can also do:
a != ato test ifais NaN.There is also
isfinite(),isinf(),isnormal(), andsignbit()macros inmath.hin C99.C99 also has
nanfunctions:(Reference: n1256).
Docs INFINITY
Docs NAN