0

我正在处理大整数(unsigned 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;
}
4

2 回答 2

3

y < 0将永远是假的,任何 xor 0 都将永远是那个东西(你错过了<以比 更高的优先级评估的东西^吗?)。

因此,除非x + ymod<the max value>恰好等于 0,否则您将抛出(并且可能似乎总是在实践中抛出,除非您设计了特定的输入)。

也许你的意思是这样的:if((std::numeric_limits<unsigned long long>::max() - y) < z) throw ...;

于 2015-04-21T17:07:56.463 回答
2

你有两个问题。主要的一个是运算符优先级<高于^。这是编译启用所有警告的一个很好的理由,因为 gcc 和 clang 都会给我一个关于这个表达式的警告并建议括号!

编译器评估的您的表达式实际上是:

if ( (y+z) ^ (y < 0) )

由于y < 0评估为0,那只是:

if (y+z)

这显然是true。但即使你的括号是正确的,如:

if (((y+z) ^ y) < 0) { ... }

那个表情很琐碎false。它仍然具有unsigned long long永远不会评估为的类型< 0

于 2015-04-21T17:08:26.793 回答