我正在處理大整數(無符號long long)並需要防範溢出條件。無論代碼拋出異常,如果有實際上是一個:大數字的C++溢出檢測(無符號long long)
try
{
unsigned long long y = std::numeric_limits<unsigned long long>::max() - 2;
unsigned long long z = 1;
int size = - 1;
if((y+z)^y < 0) //If y+z causes overflow its sign will be changed => y and (y+z) will have opposite signs
throw std::overflow_error("overflow of y+z");
//int* myarray= new int[size]; VS Debug Library catches it earlier than catch()
printf("%d\n", y*(y+z));
}
catch(exception& e)
{
cout << e.what() << endl;
}
因爲它是最大的數據類型(64位)已經,沒有足夠的空間來促進更大的東西的。
新代碼:
try
{
unsigned long long int y = std::numeric_limits<unsigned long long int>::max() - 2;
unsigned long long int z = std::numeric_limits<unsigned long long int>::max()/2;
unsigned long long delta = std::numeric_limits<unsigned long long int>::max() - y;
int size = - 1;
if(z > delta) //If y+z causes overflow its sign will be changed => y and (y+z) will have opposite signs
throw std::overflow_error("overflow of y+z");
//int* myarray= new int[size]; VS Debug Library catches it earlier than catch()
printf("%d\n", (y+z));
}
catch(exception& e)
{
cout << e.what() << endl;
}
相關:http://stackoverflow.com/questions/199333/how-to-detect-integer-overflow-in-c-c – NathanOliver