C ++中的无符号整数 [英] Unsigned integer in C++
问题描述
我编写以下代码:
#include <iostream>
using namespace std;
int main() {
unsigned int i=1;
i=i-3;
cout<<i;
return 0;
}
输出是一个垃圾值,这是可以理解的.
现在,我编写以下代码:
The output is a garbage value, which is understandable.
Now I write the following code:
#include <iostream>
using namespace std;
int main() {
unsigned int i=1;
i=i-3;
i=i+5;
cout<<i;
return 0;
}
现在输出为3.这是怎么回事?这里的垃圾值是如何加5的?
Now the output is 3. What's happening here? How is the garbage value being added by 5 here?
推荐答案
在大钟面上绘制 unsigned int
的值的想法,最大可能值(UINT_MAX)接近零.
Think of the values of unsigned int
being drawn on a large clock face with the largest possible value (UINT_MAX) being next to zero.
从1减去3将使您向后移动3个位置(这给您提供UINT_MAX-1),向此位置加5将使您向前移动5个位置.
Subtracting 3 from 1 moves you 3 places back on the clock (which gives you UINT_MAX - 1), and adding 5 to this moves you 5 places forward.
净效果是将2加1,但重要的是要知道 intermediate 值已由C ++标准完美定义.它不是不是垃圾,而是与您平台上的 UINT_MAX
的值有关.
The net effect is to add 2 to 1, but it's important to know that the intermediate value is perfectly well defined by the C++ standard. It is not garbage, but related to the value of UINT_MAX
on your platform.
请注意,此溢出的明确定义的性质对于 signed
类型而言不是正确的.在C ++中,溢出 signed
类型的行为是 undefined .
Note that the well-defined nature of this overflow is not true for signed
types. The behaviour on overflowing a signed
type is undefined in C++.
这篇关于C ++中的无符号整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!