You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行时与constexpr环境下NaN比较结果为何不一致?

MSVC下NaN与INFINITY比较的异常行为问题

由于尚未使用C++23,我自行实现了constexpr bool isfinite(Float)函数,但CI检测显示MSVC存在异常。根据IEEE 754规则,NaN除!=外与任何值的比较结果都应为false,但测试中发现了不符合预期的情况:

#include <cassert>
#include <limits>

// 声明前提假设:
static_assert(std::numeric_limits<float>::is_iec559);
static_assert(std::numeric_limits<float>::has_quiet_NaN);
static_assert(std::numeric_limits<float>::has_infinity);
static_assert(std::is_same_v<decltype(NAN), decltype(INFINITY)>);
static_assert(std::is_same_v<float, decltype(INFINITY)>);


int main() {
    static_assert(INFINITY == std::numeric_limits<float>::infinity()); // 显然成立!
    assert(INFINITY == std::numeric_limits<float>::infinity()); // 显然成立。
    assert(not (NAN < std::numeric_limits<float>::infinity())); // NaN比较始终为false,符合预期。
    assert(NAN < INFINITY); // 这怎么会通过?!
    static_assert(NAN < INFINITY); // 这也不应该通过!
    static_assert(NAN < std::numeric_limits<float>::infinity()); // 这个同样不该通过!
}

在Clang和GCC中,上述代码里那些不符合IEEE 754规则的断言会触发预期的错误,但MSVC却允许这些断言通过。这是怎么回事?是否属于实现定义行为?

内容的提问来源于stack exchange,提问作者Ben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 06:40:53