NaN 生成函数的 "char-sequence" 参数有什么用?

What is the "char-sequence" argument to NaN generating functions for?

除了 NAN 宏,C99 有两种方法可以为浮点数生成 NaN 值,nanf(const char *tagp) 函数和 strtof("NAN(char-sequence)").

这两种生成 NaN 的方法都采用可选的字符串参数(nanf() 中的 *tagp 和 strtof 方法中的字符序列)。这个字符串参数到底做了什么?我一直无法找到您如何使用它的任何具体示例。从 cppreference.com 我们有:

The call nan("string") is equivalent to the call strtod("NAN(string)", (char**)NULL);

The call nan("") is equivalent to the call strtod("NAN()", (char**)NULL);

The call nan(NULL) is equivalent to the call strtod("NAN", (char**)NULL);

并且 nan(3) 说:

These functions return a representation (determined by tagp) of a quiet NaN. [snip] The argument tagp is used in an unspecified manner. On IEEE 754 systems, there are many representations of NaN, and tagp selects one.

这并没有真正告诉我可以为 tagp 字符串使用什么,也没有告诉我为什么要使用它。是否有此标记字符串的有效选项的列表,使用默认选项的原因是什么 nanf(NULL)?

This doesn't really tell me what I can use for the tagp string or why I'd ever want to use it.

某些浮点标准(例如 IEEE-754)具有多个不同的 NaN 值。此 nan 函数规范允许实现 select 特定的 NaN 表示,具体取决于实现可能指定的方式的字符串。

Tl;Dr : tagp 参数使您能够拥有不同的 NAN 值。

这是 nan(3) 的手册页,它提供了更多关于 tagp 的信息。

主要是:

The nan() functions return a quiet NaN, whose trailing fraction field contains the result of converting tagp to an unsigned integer.

这使您能够拥有不同的 NAN 值。

特别来自 C99 基本原理 doc:

Other applications of NaNs may prove useful. Available parts of NaNs have been used to encode auxiliary information, for example about the NaN’s origin. Signaling NaNs might be candidates for filling uninitialized storage; and their available parts could distinguish uninitialized floating objects. IEC 60559 signaling NaNs and trap handlers potentially provide hooks for maintaining diagnostic information or for implementing special arithmetics.

它有一个实现 here。请注意,如评论中所述,这可能符合也可能不符合标准。但是,它应该让您了解 tagp 的用途。

如man page,可以看到上面提到的替换:

nan("1") = nan (7ff8000000000001)
nan("2") = nan (7ff8000000000002)

完整的手册页在这里:

NAN(3) BSD Library Functions Manual
NAN(3)

NAME nan -- generate a quiet NaN

SYNOPSIS #include

 double
 nan(const char *tagp);

 long double
 nanl(const char *tagp);

 float
 nanf(const char *tagp);

DESCRIPTION The nan() functions return a quiet NaN, whose trailing fraction field contains the result of converting tagp to an unsigned integer. If tagp is too large to be contained in the trailing fraction field of the NaN, then the least significant bits of the integer represented by tagp are used.

SPECIAL VALUES If tagp contains any non-numeric characters, the function returns a NaN whos trailing fraction field is zero.

If tagp is empty, the function returns a NaN whos trailing fraction field is zero.

STANDARDS The nan() functions conform to ISO/IEC 9899:2011.

BSD July 01, 2008