Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define NaN in portable C without "error C2124: divide or mod by zero"

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?

like image 701
truf Avatar asked Oct 15 '25 08:10

truf


1 Answers

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 type float 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.

like image 103
Eric Postpischil Avatar answered Oct 16 '25 22:10

Eric Postpischil