浮点除以零而不是constexpr [英] Floating point division by zero not constexpr

查看:104
本文介绍了浮点除以零而不是constexpr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译时:

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)失败,给出错误:

The compiler (gcc 4.9.2, -std=c++11 or c++14) fails, giving error:

(1.23e+2 / 0.0)' is not a constant expression
  constexpr double y = x / 0.0;

在确定 y 可以是 constexpr 吗?

作为参考,这似乎是一种方法:

For reference, this seems to be the way to do it:

static constexpr double z = std::numeric_limits<double>::quiet_NaN();
static constexpr double w = std::numeric_limits<double>::infinity();


推荐答案

Infinity是实现定义的结果,标准没有要求 IEEE浮点,并且除以0正式是未定义的行为常量表达式将未定义的行为排除在外行为

Infinity is an implementation defined result, the standard does not require IEEE floating point and division by zero is formally undefined behavior and constant expression have an exclusion for undefined behavior.

摘自C ++标准草案 5.6 [expr.mul]

From the draft C++ standard section 5.6 [expr.mul]:


二进制/运算符产生商,二进制%运算符
产生第一个表达式除以$的余数b $ b秒。 如果/或%的第二个操作数为零,则行为为
未定义。

这篇关于浮点除以零而不是constexpr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆