c - 关于无符号整数下溢的 C 行为问题

标签 c integer types integer-overflow underflow

我在很多地方都读到,无符号整数溢出在 C 中定义明确,与有符号整数溢出不同。

underflow一样吗?

例如:

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

谢谢。

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

最佳答案

§6.2.5,第 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(有符号和无符号整数转换):

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 - 关于无符号整数下溢的 C 行为问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2760502/

相关文章:

c - 将 $n 替换为字符串中的 n

函数中无法识别字符数组

c - 关于这个问题的快速问题,为什么它不在字符串上打印出第二个值(转换后的第二个值)?

Python 嵌套的整数列表未按预期返回

sql - 货币和整数数据类型之间的区别

c - C read() 线程安全吗?

c - if(varName) 和 if(varName!=NULL) 有什么区别?

java - Java 中 != 和 == 运算符如何处理整数?

c++ - pow 积分值

f# - 您如何在F#中定义货币类型