关于无符号整数下溢的 C 行为问题 [英] Question about C behaviour for unsigned integer underflow

查看:31
本文介绍了关于无符号整数下溢的 C 行为问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在很多地方都读到过,与有符号的对应物不同,无符号整数溢出在 C 中是明确定义的.

I have read in many places that unsigned integer overflow is well-defined in C unlike the signed counterpart.

下溢一样吗?

例如:

unsigned int x = -1; // Does x == UINT_MAX?

谢谢.

我不记得在哪里,但我在某处读到无符号整数类型的算术是模块化的,所以如果是这种情况,那么 -1 == UINT_MAX mod (UINT_MAX+1).

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).

推荐答案

§6.2.5, 第 9 段:

§6.2.5, paragraph 9:

涉及无符号的计算操作数永远不会溢出,因为无法表示的结果生成的无符号整数类型是以一的数为模减少大于最大值可以用结果表示输入.

A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.

抱歉,引用错误,但结果还是被钉住了.正确的参考是 §6.3.1.3(有符号和无符号整数转换):

Sorry, wrong reference, but the result is still pinned down. The correct reference is §6.3.1.3 (signed and unsigned integer conversion):

如果新类型是无符号,值被转换为反复加减一个超过可以达到的最大值以新类型表示,直到该值在新的范围内类型.

if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

是的,x == UINT_MAX.

这篇关于关于无符号整数下溢的 C 行为问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆