C中的无符号整数下溢 [英] Unsigned integer underflow in C

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

问题描述

我在网站上看到了多个问题,这些问题解决了无符号整数上溢/下溢的问题.关于下溢的大多数问题都询问有关将负数分配给无符号整数的问题.我不清楚当从另一个 unsigned int 中减去一个 unsigned int 时会发生什么. a-b ,结果为负.该标准的相关部分是:

I've seen multiple questions on the site addressing unsigned integer overflow/underflow. Most of the questions about underflow ask about assigning a negative number to an unsigned integer; what's unclear to me is what happens when an unsigned int is subtracted from another unsigned int e.g. a - b where the result is negative. The relevant part of the standard is:

涉及无符号操作数的计算永远不能溢出,因为不能用所得的无符号整数类型表示的结果的模数要比该所得类型可以表示的最大值大一模.

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.

在这种情况下,您如何解释精简" ?这是否意味着 UINT_MAX + 1 添加到否定结果,直到> = 0 ?

In this context how do you interpret "reduced"? Does it mean that UINT_MAX+1 is added to the negative result until it is >= 0?

我看到要解决的要点是此问题(基本上说该标准选择谈论溢出,但关于的要点也适用于下溢),但我仍然不清楚:

I see that the main point is addressed by this question (which basically says that the standard chooses to talk about overflow but the main point about modulo holds for underflow too) but it's still unclear to me:

假设 a-b 的结果为 -1 ;根据标准,操作 -1%(UINT_MAX + 1)将返回 -1 (如

Say the result of a-b is -1; According to the standard, the operation -1%(UINT_MAX+1) will return -1 (as is explained here); so we're back to where we started.

这可能是过于腐的,但这 modulo 表示与C的计算模相反的数学模吗?

This may be overly pedantic, but does this modulo mean a mathematical modulo as opposed to C's computational modulo?

推荐答案

首先,低于给定整数类型最小值的结果在C中不称为下溢".术语下溢"保留用于浮动点类型和含义完全不同的东西.超出整数类型的范围始终是溢出,无论您跨越范围的哪一端.因此,在这种情况下,您没有看到语言规范谈论下溢"行为这一事实并没有任何意义.

Firstly, a result that is below the minimum value of the given integer type is not called "underflow" in C. The term "underflow" is reserved for floating-point types and means something completely different. Going out of range of an integer type is always overflow, regardless of which end of the range you cross. So the fact that you don't see the language specification talking about "underflow" doers not really mean anything in this case.

第二,您对"reduced"一词的含义绝对正确.最终值是通过从数学"结果中加上(或减去) UINT_MAX + 1 直到返回到 unsigned int 的范围来定义的.这也与欧几里得的模"运算相同.

Secondly, you are absolutely right about the meaning of the word "reduced". The final value is defined by adding (or subtracting) UINT_MAX+1 from the "mathematical" result until it returns into the range of unsigned int. This is also the same thing as Euclidean "modulo" operation.

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

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