Can an integer be NaN in C++?

混江龙づ霸主 提交于 2019-12-28 06:19:38

问题


Can I set an int to NaN? If yes, then how can I check if an int is NaN or not?


回答1:


No, NaN is a floating point value.

Every possible value of an int is a number.

Edit

The standard says:

6.2.6.2 40) 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 representation other than as part of an exceptional condition such as an overflow, and this cannot occur with unsigned types.

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




回答2:


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

Integer NaN

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




回答3:


No, you cannot set an int to NaN.




回答4:


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.




回答5:


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

int myfunc(args, int* realReturn);

The returned int is an error code.

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

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


来源:https://stackoverflow.com/questions/3949457/can-an-integer-be-nan-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!