NaN Literal in C?

假装没事ソ 提交于 2019-11-29 03:14:10

In C99's <math.h>

  7.12  Mathematics <math.h>
   [#5] 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.           |

5.2.4.2.2/3:

floating types may be able to contain other kinds of floating-point numbers, such as ... infinities and NaNs. A NaN is an encoding signifying Not-a-Number. A quiet NaN propagates through almost every arithmetic operation without raising a floating-point exception; a signaling NaN generally raises a floating-point exception when occurring as an arithmetic operand.

7.12/5 (math.h):

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.

So you can get a value if your implementation supports NaNs at all, and if some or all of those NaNs are quiet. Failing that you're into implementation-defined territory.

There's also a slight worry with some of these floating-point macros that the compiler front-end might not know whether it supports the feature or not, because it produces code that can run on multiple versions of an architecture where support varies. I don't know whether that applies to this macro, but it's another situation where you're into implementation-defined territory - the preprocessor might conservatively claim that it doesn't support the feature when actually the implementation as a whole, as you're using it, does.

Using NAN is better, but if you're on a system that has NaNs, 0.0/0.0 is an easy way to get one...

In C you can write a NaN floating point literal in the following way.

const unsigned long dNAN[2] = {0x00000000, 0x7ff80000};
const double LITERAL_NAN = *( double* )dNAN;

Please note that, this is not a standard way. On Microsoft C, it works fine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!