Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

c++ - Is casting of infinity to integer undefined?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...