C++ 中的整数可以是 NaN 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3949457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:07:11  来源:igfitidea点击:

Can an integer be NaN in C++?

c++nan

提问by MBZ

Can I set an intto NaN? If yes, then how can I check if an intis NaNor not?

我可以设置intNaN吗?如果是,那么我如何检查是否intNaN

回答by DerKuchen

No, NaN is a floating point value.

不,NaN 是一个浮点值。

Every possible value of an intis a number.

an 的每个可能值int都是一个数字。

Edit

编辑

The standard says:

标准说:

6.2.6.240) Some combinations of padding bits might generate trap representations, for example, if one padding bit is a parity bit. Regardless, no arithmetic operation on valid values can generate a trap representationother than as part of an exceptional condition such as an overflow, and this cannot occur with unsigned types.

6.2.6.240) 某些填充位组合可能会产生陷阱表示,例如,如果一个填充位是奇偶校验位。无论如何,除了作为异常情况(如溢出)的一部分之外,任何对有效值的算术运算都不能生成陷阱表示,并且这不会发生在无符号类型中。

So there maybe some implementation specific invalid integer values, but there is no defined way to generate them.

所以可能有一些特定于实现的无效整数值,但没有定义的方法来生成它们。

回答by Mark Rushakoff

Generally (and specifically in the case of C++, to the best of my knowledge): no.

一般来说(特别是在 C++ 的情况下,据我所知):没有

Integer NaN

Most fixed sized integer formats do not have any way of explicitly indicating invalid data.

整数 NaN

大多数固定大小的整数格式没有任何方式明确指示无效数据。

回答by Manoj R

You don't have any specific int value as Nan. What normally people do is use some large integer to represent this value. IF it is unsigned int then its normally use -1.

您没有任何特定的 int 值作为 Nan。人们通常做的是使用一些大整数来表示这个值。如果它是 unsigned int 那么它通常使用 -1。

回答by codaddict

No, you cannot set an intto NaN.

不,您不能将 an 设置int为 NaN。

回答by gturbo

I think the most proper API to handle failures is to return a second integer error code in your api like:

我认为处理失败的最合适的 API 是在你的 api 中返回第二个整数错误代码,如:

int myfunc(args, int* realReturn);

The returned int is an error code.

返回的 int 是一个错误代码。

The previous output is passed as a pointer in calling code:

前面的输出在调用代码中作为指针传递:

int myInt;
if (myFunc(args, &myInt) != 0) {
//handle error
}