[英]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.