C中的二进制补码加法溢出 [英] Two's complement addition overflow in C
问题描述
我在C中看到一个错误的代码,该代码用于检查加法是否导致溢出。 char
可以很好地工作,但是当参数为 int
时给出错误的答案,而我不知道为什么。
这是带有 short
参数的代码。
I saw a buggy code in C which was used to check whether addition results in overflow or not. It works fine with char
, but gives incorrect answer when arguments are int
and I couldn't figure why .
Here's the code with short
arguments.
short add_ok( short x, short y ){
short sum = x+y;
return (sum-x==y) && (sum-y==x);
}
此版本工作正常,将参数更改为<$ c $时会出现问题c> int (您可以使用 INT_MAX
进行检查)
您能看到这里有什么问题吗?
This version works fine, problem arise when you change arguments to int
( you can check it with INT_MAX
)
Can you see what's wrong in here ?
推荐答案
因为补码为2s,所以整数可以排列成一个圆(在模运算)。先加上y,再减去y,始终可以回到起点(尽管行为未定义)。
Because in 2s complement, the integers can be arranged into a circle (in the sense of modulo arithmetic). Adding y and then subtracting y always gets you back where you started (undefined behaviour notwithstanding).
这篇关于C中的二进制补码加法溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!