如标题所示,我很好奇 unsigned int
(或类似 NSUInteger
、u_int_blah
的东西,但我认为这些是同一事物的所有 typedef
)都有效。例如,当它们的值低于零时,是否会引发异常?会不会出错?一个具体示例是间接将值设置为负数。
for (unsigned int x = 5; x > -10; x--) {
// will x ever reach below zero, or will the loop terminate
}
此外,另一种间接设置它的方法是让用户输入它。
printf("Enter a number");
unsigned int x;
scanf("%ud", &x); // user enters something like -29
所以真的,我有三个问题。是什么阻止了 unsigned int 被分配给负数 (unsigned int x = - 3
)。这种行为是如何实现的(通过编译器,或通过其他方式)。当 unsigned int 被(直接或间接)赋给一个负值时会发生什么。数据是否损坏?它溢出了吗?
谢谢
最佳答案
unsigned 与 signed 比较时,都会被转为 unsigned。该过程与数据在内存中的存储方式有关。 在二进制中,负数(如 -3)将存储为:
-3 : 1111 1111 1111 1101
3 : 0000 0000 0000 0011
你可以看出 -3 可以是这样的:
// result : 0000 0000 0000 0011
result = for_every_bit_of_3( not **ThisBit** );
// result : 1111 1111 1111 1100
result = result + 1;
// result : 1111 1111 1111 1101
所以循环:
for (unsigned int x = 5; x > -10; x--) {
// will x ever reach below zero, or will the loop terminate
}
会像
// 4,294,967,286 is what -10 cast to unsigned
for (unsigned int x = 5; x > 4294967286; x--) {
// will x ever reach below zero, or will the loop terminate
}
关于c++ - 无符号整数如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22800589/