gpt4 book ai didi

c++11 - 浮点除以零不是 constexpr

转载 作者:行者123 更新时间:2023-12-05 00:59:39 25 4
gpt4 key购买 nike

编译时:

constexpr double x {123.0};
constexpr double y = x / 0.0;
std::cout << x << " / 0 = " << y << "\n";

编译器(gcc 4.9.2,-std=c++11 或 c++14)失败,给出错误:
(1.23e+2 / 0.0)' is not a constant expression
constexpr double y = x / 0.0;

在决定是否 y 时,结果 (Inf) 有何相关性可以是 constexpr 还是不是?

作为引用,这似乎是这样做的方法:
static constexpr double z = std::numeric_limits<double>::quiet_NaN();
static constexpr double w = std::numeric_limits<double>::infinity();

最佳答案

Infinity 是实现定义的结果,标准不要求 IEEE floating point被零除的形式是 undefined behaviorconstant expression have an exclusion for undefined behavior .

来自 C++ 标准草案部分 5.6 [expr.mul]:

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined.

关于c++11 - 浮点除以零不是 constexpr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30459773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com