这个条件是否足以满足乘法运算中的溢出检查

问题描述:

    int isOverflow(uint a, uint b) {
        // a and b are unsigned non-zero integers.
        uint c = a * b;

        if (c < ( a > b ? a : b))
                return 1;
        else
                return 0;
}

我想念什么吗?我认为上面的代码片段会起作用.

Am I missing something ? I think the above snippet will work.

编辑:我看过其他解决方案,例如

EDIT : I have seen other solutions like multiplication of large numbers, how to catch overflow which uses some fancy methods to check it. But to me above simple solution also looks correct. Thats why I am asking this question.

很容易通过发现异常来证明这是错误的:

It's easy to prove this is wrong by finding an exception:

请考虑以下两个8位无符号值:a = 0x1Fb = 0xF.

Consider these two 8-bit unsigned values: a = 0x1F and b = 0xF.

c = a * b
c = 0x1F * 0xF
c = 0xD1              (Overflow! The real answer is 0x1D1)

c < ( a > b ? a : b)
0xD1 < 0x1F           => False  (Wrong!)

正确的答案是此处.