繁体   English   中英

C ++标准对于在目标类型范围之外的类型的转换结果的结果有何评价?

[英]What does the C++ standard say about results of casting value of a type that lies outside the range of the target type?

最近我不得不执行从float到16位整数的一些数据类型转换。 基本上我的代码简化为以下内容

float f_val = 99999.0;
short int si_val = static_cast<short int>(f_val);

// si_val is now -32768

这个输入值是一个问题,在我的代码中,我忽略了检查浮点值的限制,所以我可以看到我的错,但它让我想知道语言的确切规则,当一个人必须做这种笨拙的演员。 我有点惊讶地发现演员的价值是-32768。 此外,只要float的值超过16位整数的限制,这就是我得到的值。 我用谷歌搜索了这个,但发现了一个令人惊讶的缺乏关于它的详细信息。 我能找到的最好的是来自cplusplus.com的以下内容

从某个较小的整数类型转换为int,或从float转换为double,称为提升,并保证在目标类型中生成完全相同的值。 算术类型之间的其他转换可能并不总是能够完全表示相同的值:

 If the conversion is from a floating-point type to an integer type, the value is truncated (the decimal part is removed). The conversions from/to bool consider false equivalent to zero (for numeric types) and to null pointer (for pointer types); and true equivalent to all other values. Otherwise, when the destination type cannot represent the value, the conversion is valid between numerical types, but the value is implementation-specific (and may not be portable). 

这个结果是实现定义的建议并不让我感到惊讶,但我听说cplusplus.com并不总是可靠的。

最后,当从32位整数到16位整数执行相同的转换(同样具有16位范围的值)时,我看到结果清楚地表明整数溢出。 虽然我对此并不感到惊讶,但由于与float类型的演员不一致而增加了我的困惑。

我无法访问C ++标准,但是这里有很多C ++人员,所以我想知道标准在这个问题上说了些什么? 为了完整起见,我使用的是g ++版本4.6.3。

你对自己所读到的内容有疑问。 转换没有明确的行为,这与您在问题中引用的内容相矛盾。

4.9浮动积分转换[conv.fpint]

1浮点类型的prvalue可以转换为整数类型的prvalue。 转换截断; 也就是说,丢弃小数部分。 如果截断的值无法在目标类型中表示,则行为未定义。 [ 注意:如果目的地类型是bool ,请参阅4.12。 - 结束说明 ]

您可能获得的一个可能有用的允许结果是崩溃。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM