考慮一個典型的絕對值函數(其中爲參數的緣故整體式最大尺寸爲長):有沒有一種安全的方法來獲得有符號整數的無符號絕對值,而不會觸發溢出?
unsigned long abs(long input);
一個天真的實現,這可能看起來像:
unsigned long abs(long input)
{
if (input >= 0)
{
// input is positive
// We know this is safe, because the maximum positive signed
// integer is always less than the maximum positive unsigned one
return static_cast<unsigned long>(input);
}
else
{
return static_cast<unsigned long>(-input); // ut oh...
}
}
這代碼觸發未定義的行爲,因爲input
的否定可能溢出,並且觸發有符號的整數溢出是未定義的行爲。例如,在2s補碼機器上,std::numeric_limits<long>::min()
的絕對值將大於std::numeric_limits<long>::max()
。
圖書館作者可以做些什麼來解決這個問題?
很好的答案,儘管你自己的問題,但+1。 – Bathsheba