是否将无穷大转换为整数未定义? [英] Is casting of infinity to integer undefined?
问题描述
将无穷大(由float表示)强制转换为整数是未定义的行为吗?
标准说:
4.10浮点积分转换
浮点类型的prvalue可以转换为浮点类型的prvalue整数类型.转换被截断;即小数部分被丢弃.如果截断的值不能,则行为未定义以目标类型表示.
但是我不能确定无法表示截断的值"是否包含无穷大.
我试图理解为什么 std :: numeric_limits< int> ::: infinity()
和 static_cast< int>(std :: numeric_limits< float> :: infinity())
有不同的结果.
#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;返回0;}
输出:
0-2147483648
std :: numeric_limits< int> :: infinity()
的结果
由于无穷大的截断仍然是无穷大,并且无穷大不能用 int
表示(我希望这部分没有问题),所以行为是不确定的.
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.
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.
这篇关于是否将无穷大转换为整数未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!