I have an old legacy code written in pure C. It's crossplatform. I need to define a NaN constant in it. My approach was:
const double _NAN = 0.0/0.0;
Unfortunately when I tried to build the code on Win machine (VS 2022) I've got "error C2124: divide or mod by zero"
.
I'm pretty sure there is a parameter for parameter for MSVC compiler that disables it, but that's a public project and MS VS is only one of IDE which could be used to build it. And I don't want ask users to change defaults in a specific environment.
I guess I could use HEX value for NaN but suppose I'll face with endiannes... Which imply i'll need to detect endiannes in portable way.
Are there any better options to define NaN for double in C in a crossplatform way?
You can include <math.h>
and use NAN
. C 1999 and C 2018 7.12 5 both say:
The macro
NAN
is defined if and only if the implementation supports quiet NaNs for the
float
type. It expands to a constant expression of typefloat
representing a quiet NaN.
You can use it for the double
type, and, if you want to deal with cases in which it is not defined by the C implementation, you can test with #if defined NAN
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With