Why is numeric_limits<int>::max() > numeric_limits<int>::infinity()?

喜夏-厌秋 提交于 2019-12-04 22:22:15

The function numeric_limits<T>::infinity() makes sense for those T for which numeric_limits<T>::has_infinity returns true.

In case of T=int, it returns false. So that comparison doesn't make sense, because numeric_limits<int>::infinity() does not return any meaningful value to compare with.

If you read e.g. this reference you will see a table showing infinity to be zero for integer types. That's because integer types in C++ can't, by definition, be infinite.

Suppose, conversely, the standard did reserve some value to represent inifity, and that numeric_limits<int>::infinity() > numeric_limits<int>::max(). That means that there would be some value of int which is greater than max(), that is, some representable value of int is greater than the greatest representable value of int.

Clearly, whichever way the Standard specifies, some natural understanding is violated. Either inifinity() <= max(), or there exists x such that int(x) > max(). The Standard must choose which rule of nature to violate.

I believe they chose wisely.

numeric_limits<int>::infinity() returns the representation of positive infinity, if available.

In case of integers, positive infinity does not exists:

cout << "int has infinity: " << numeric_limits<int>::has_infinity << endl;

prints

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