Is casting of infinity to integer undefined?

冷暖自知 提交于 2019-12-23 06:47:21

问题


Is the casting of infinity (represented by float) to an integer an undefined behavior?

The standard says:

4.10 Floating-integral conversions

A prvalue of a floating point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type.

but I can't tell whether "truncated value cannot be represented" covers infinity.

I'm trying to understand why std::numeric_limits<int>::infinity() and static_cast<int>(std::numeric_limits<float>::infinity() ) have different results.

#include <iostream>
#include <limits>

int main ()
{
    std::cout << std::numeric_limits<int>::infinity () << std::endl;
    std::cout << static_cast<int> (std::numeric_limits<float>::infinity () ) << std::endl;
    return 0;
}

Output:

0  
-2147483648  

The result of std::numeric_limits<int>::infinity() is well defined and equal to 0, but I can't find any information about casting infinity.


回答1:


You said

I can't tell whether "truncated value cannot be represented" covers infinity

but it all boils down to

What is the result of truncating infinity.

The C standard (incorporated into C++ via 26.9) answers that quite plainly:

Since truncation of infinity is still infinity, and infinity cannot be represented in int (I hope there's no question about this part), the behavior is undefined.




回答2:


Casting of infinity to integer is undefined.

The behavior is undefined if the truncated value cannot be represented in the destination type.

Says it all. Since truncation removes precision but not magnitude, a truncated infinity is still infinity and integers cannot represent infinity.




回答3:


I'm trying to understand why std::numeric_limits<int>::infinity() and static_cast<int>(std::numeric_limits<float>::infinity() ) have different results.

The standard says: 18.3.2.4

static constexpr T infinity() noexcept;

47 Representation of positive infinity, if available. [216]

48 Meaningful for all specializations for which has_infinity != false. Required in specializations for which is_iec559 != false.

--- edit ---

According to 18.3.2.7/1 [numeric.special]

1 All members shall be provided for all specializations. However, many values are only required to be meaningful under certain conditions (for example, epsilon() is only meaningful if is_integer is false). Any value that is not “meaningful” shall be set to 0 or false.



来源:https://stackoverflow.com/questions/38795544/is-casting-of-infinity-to-integer-undefined

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