nan() 函数的参数

The argument of the nan() function

有时需要获取NaN值(例如,从函数中将return它作为错误值)。 С++11 提供了 double nan(const char* tagp); 函数来得到 NaN 参见 doc。此函数获取 C 字符串参数 tagp 其中:

can be used by library implementations to distinguish different NaN values in a implementation-specific manner. If this is an empty string (""), the function returns a generic NaN value

我想更深入地了解这个功能。有人可以更详细地解释一下吗

  1. 除了空字符串""之外还可以使用什么tagp值?我在哪里可以找到可能值的列表?
  2. 如果传递的 tagp 参数错误或编译器不支持会怎样?
  3. 在跨平台代码中使用这个特定于实现的函数是否安全?

С++11 provides the double nan(const char* tagp);

一些 C 章节 (C17 § 7.12.11.2)

Description
2 The nan, nanf, and nanl functions convert the string pointed to by tagp according to the following rules. The call nan("n-char-sequence") is equivalent to strtod("NAN(n-char-sequence)", (char**)NULL); the call nan("") is equivalent to strtod("NAN()",(char**)NULL). If tagp does not point to an n-char sequence or an empty string, the call is equivalent to strtod("NAN",(char**)NULL). ...

Returns
3 The nan functions return a quiet NaN, if available, with content indicated through tagp. If the implementation does not support quiet NaNs, the functions return zero.


  1. 除了空字符串""之外还可以使用哪些tagp值?我在哪里可以找到可能值的列表?

tagp 指向 0-9、A-Z、a-z、_ 个字符的序列。

  1. 如果编译器不支持传递的 tagp 参数会怎样?

如果 C/C++ 规范不支持,“调用等同于 strtod("NAN",(char**)NULL)”。这会导致实现定义的结果。

  1. 在跨平台代码中使用这个特定于实现的函数是否安全?

是的,安全的是 未定义的行为 不会发生。然而,派生的含义和 NAN 是特定于实现的。


n-char-sequence 解释为 NAN 有效载荷的十进制表示是受上述限制的可能结果。

另见 What uses do floating point NaN payloads have? and wiki NaN