关于无符号整数下溢的 C 行为问题
我在很多地方读到,与有符号整数溢出不同,C 中无符号整数溢出是明确定义的。
下溢是一样的吗?
例如:
unsigned int x = -1; // Does x == UINT_MAX?
谢谢。
我不记得在哪里,但我在某处读到无符号整数类型的算术是模块化的,所以如果是这种情况,那么 -1 == UINT_MAX mod (UINT_MAX+1)。
I have read in many places that unsigned integer overflow is well-defined in C unlike the signed counterpart.
Is underflow the same?
For example:
unsigned int x = -1; // Does x == UINT_MAX?
Thanks.
I can't recall where, but i read somewhere that arithmetic on unsigned integral types is modular, so if that were the case then -1 == UINT_MAX mod (UINT_MAX+1).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
§6.3.1.3 有符号和无符号整数,第 2 段:
所以是的,
x == UINT_MAX
。§6.3.1.3 Signed and unsigned integers, paragraph 2:
So yes,
x == UINT_MAX
.-1,当表示为 2 的补码时,无论您的数字有多少位,都等于 0xFF...F。在无符号数字空间中,该值是可能的最大值(即设置所有位)。因此,是的,x == UINT_MAX。以下代码在 C99 严格编译器上发出“1”:
-1, when expressed as a 2's complement number, amounts to 0xFF...F for how ever many bits your number is. In an unsigned number space that value is the maximum value possible (i.e. all the bits are set). Therefore yes, x == UINT_MAX. The following code emits "1" on a C99 strict compiler:
你混合了有符号和无符号的数字,这是不酷的。
You are mixing signed and unsigned numbers, which is uncool.