当我在断言测试运行期间遇到一个奇怪的问题时,我正在自学CSAPP并得到一个奇怪的结果.
我不知道该怎么开始这个问题,所以让我先得到代码(文件名在评论中可见):
// File: 2.30.c
// Author: iBug
int tadd_ok(int x, int y) {
if ((x ^ y) >> 31)
return 1; // A positive number and a negative integer always add without problem
if (x < 0)
return (x + y) < y;
if (x > 0)
return (x + y) > y;
// x == 0
return 1;
}
Run Code Online (Sandbox Code Playgroud)
// File: 2.30-test.c
// Author: iBug
#include <assert.h>
int tadd_ok(int x, int y);
int main() {
assert(sizeof(int) == 4); …Run Code Online (Sandbox Code Playgroud) 是否可以在编译时检测或防止整数溢出而不是在运行时?
如果未检测到溢出并且在运行时发生溢出,是否可以检测到?我在某处读到,如果某个操作出现溢出,处理器将设置一个特定的标志.
如何读取处理器的特定标志?我应该问这是一个单独的问题吗?
编辑:
我的问题是签名和无符号溢出.当我们有一个无符号变量时,它仍然会溢出并将自身设置为0或接近0的东西,对吧?还是我缺少的东西?
我想知道是否x - y溢出。
下面是我的代码。
#include <stdio.h>
/* Determine whether arguments can be subtracted without overflow */
int tsub_ok(int x, int y)
{
return (y <= 0 && x - y >= x) || (y >= 0 && x - y <= x);
}
int main()
{
printf("0x80000000 - 1 : %d\n", tsub_ok(0x80000000, 1));
}
Run Code Online (Sandbox Code Playgroud)
为什么我不能得到我期望的结果?
这里,base可能会溢出超出int的限制,导致运行时错误,此时我打算捕获引发的运行时错误并处理它,所以我尝试了try-catch块,但它没有被捕获。
int base=1;
try
{
base *= 10;
//some code
}
catch(...)
{
//some code
}
Run Code Online (Sandbox Code Playgroud)