c - 在没有 "error C2124: divide or mod by zero"的可移植 C 中定义 NaN

标签 c visual-studio-2022

我有一个用纯 C 编写的旧遗留代码。它是跨平台的。我需要在其中定义一个 NaN 常量。我的方法是: const double _NAN = 0.0/0.0;
不幸的是,当我尝试在 Win 机器 (VS 2022) 上构建代码时,我遇到了“error C2124: divide or mod by zero”

我很确定 MSVC 编译器的参数有一个参数可以禁用它,但这是一个公共(public)项目,MS VS 只是可用于构建它的 IDE 之一。而且我不想要求用户更改特定环境中的默认值。

我想我可以对 NaN 使用 HEX 值,但假设我将面对字节序...这意味着我需要以可移植的方式检测字节序。

是否有更好的选择以跨平台的方式在 C 中为 double 定义 NaN?

最佳答案

您可以包括 <math.h>并使用 NAN . C 1999 和 C 2018 7.12 5 都说:

The macro

NAN

is defined if and only if the implementation supports quiet NaNs for the float type. It expands to a constant expression of type float representing a quiet NaN.

您可以将它用于 double类型,并且,如果你想处理 C 实现未定义的情况,你可以使用 #if defined NAN 进行测试.

关于c - 在没有 "error C2124: divide or mod by zero"的可移植 C 中定义 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73561518/

相关文章:

c - 使用不带字符串化的#define 参数名称

c - 字符串数组并在字符串中定位字符

html - 如何在 Visual Studio 2022 中使用 Visual Studio 2019 中的 Razor 编辑器?

c# - 取消引用可能的空引用 C#

android - 安装SDK后Visual Studio android api版本不可用

azure - Visual Studio 如何选择 Azure Functions Tools 版本?

c - 从内核分配用户空间内存

C : timer inside while/loop + scanf?

c - 进程退出前打印退出状态

visual-studio - Visual Studio 2022 重复快捷方式已更改