c++ - static_cast<double>(std::nanf ("")) 定义明确吗?

标签 c++ floating-point language-lawyer nan

标题几乎要求了一切,但要提供 MCVE:

#include <cmath>

int main()
{
    float f = std::nanf("");
    double d = static_cast<double>(f);
    return 0;
}

在 MSVC 2017 下,fd 都报告为 nan,但这并不能证明什么,因为可能是 static_cast 是未定义的行为。

以类似的方式,0.0f/0.0f 产生 -nan(ind),我假设它是一个信号 nan,它是否遵循相同的定义/未定义的规则?同上inf

最佳答案

这看起来是由标准保证的,我们可以从 [expr.static.cast]p4 部分开始其中说:

An expression e can be explicitly converted to a type T if there is an implicit conversion sequence from e to T ...

隐式转换序列包含在 [over.best.ics] 中我们有以下内容:

A well-formed implicit conversion sequence is one of the following forms:
- (3.1) a standard conversion sequence,
...

标准转换序列包含在 [over.ics.scs] 中其中说:

[ Note: As described in [conv], a standard conversion sequence is either the Identity conversion by itself (that is, no conversion) or consists of one to three conversions from the other four categories. If there are two or more conversions in the sequence, the conversions are applied in the canonical order: Lvalue Transformation, Promotion or Conversion, Qualification Adjustment. — end note ]

我们有 [conv.fpprom]p1 中介绍的浮点提升案例其中说:

A prvalue of type float can be converted to a prvalue of type double. The value is unchanged.

以另一种方式doublefloat将是一个转换,这在 [conv#double]p1 中有介绍。 :

A prvalue of floating-point type can be converted to a prvalue of another floating-point type. If the source value can be exactly represented in the destination type, the result of the conversion is that exact representation. If the source value is between two adjacent destination values, the result of the conversion is an implementation-defined choice of either of those values. Otherwise, the behavior is undefined.

这种情况取决于源是否可以由目标准确表示,但无法保证。

关于浮点除以零的子问题很复杂,我在 The behaviour of floating point division by zero 的回答中对此进行了介绍。 .

关于c++ - static_cast<double>(std::nanf ("")) 定义明确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53075838/

相关文章:

c++ - BigInt 转换(gmp Bigint 到 botan bigint)

java - 使用小数指数的 Math.pow

c - 为变量分配浮点值

c++ - 为什么模板模板参数不允许在参数列表后出现 'typename'

C 内存分配器和严格的别名

c++ - 在析构函数中使用 `friend` 说明符的示例?

c++ - std::unordered_map 内部使用哈希吗?

c++ - 通过进程或 dll 的内存转储识别内存代码注入(inject)

c++ - 切换到C++11时,是否需要重新编译接口(interface)中使用STL的所有依赖库?

Python 认为 Euler 存在身份问题(cmath 返回奇怪的结果)