gpt4 book ai didi

c - 测试两个整数之和是否溢出

转载 作者:太空狗 更新时间:2023-10-29 17:05:14 24 4
gpt4 key购买 nike

来自C陷阱和陷阱

If a and b are two integer variables, known to be non-negative then to test whether a+b might overflow use:

     if ((int) ((unsigned) a + (unsigned) b) < 0 )
complain();

我不明白将两个整数之和与零进行比较如何让您知道存在溢出?

最佳答案

您看到的用于测试溢出的代码只是伪造的。

对于有符号整数,你必须像这样测试:

if (a^b < 0) overflow=0; /* opposite signs can't overflow */
else if (a>0) overflow=(b>INT_MAX-a);
else overflow=(b<INT_MIN-a);

请注意,如果两个数字之一是常量,则情况可以大大简化。

对于无符号整数,你可以这样测试:

overflow = (a+b<a);

这是可能的,因为无符号算术被定义为换行,这与有符号算术在溢出时调用未定义行为不同。

关于c - 测试两个整数之和是否溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6970802/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com