#include<stdio.h>
void main()
{
int a = -1;
unsigned int b =15;
if(b==a)
printf ("b is equal to a");
}
输出为空。负整数存储为相同正数的 2 的补码。当将整数与 unsigned int 进行比较时,通过将 2 的补码视为 unsigned int 来将整数提升为 unsigned int,此处为 15,但输出为空,即使 2 的补码为 -1是 15
最佳答案
变量a
和b
int a = -1; /* its a sign ed int, it takes 4 bytes */
unsigned int b =15;/* its a unsigned int */
如下所示
a = -1 => 1111 1111 | 1111 1111 | 1111 1111 | 1111 1111
b = 15 => 0000 0000 | 0000 0000 | 0000 0000 | 0000 1111
MSB LSB
现在,当您比较 a
和 b
时,就像
if(b==a) {
/* some code */
}
在这里,您正在两种不同类型之间进行比较==
(a
是signed
类型&b
是无符号
类型)。因此隐式编译器会将sign int
转换/提升为unsigned int
,然后执行比较==
。看这个http://port70.net/~nsz/c/c11/n1570.html#6.3.1.8算术对话规则。
现在 a
或 -1
的 unsigned
等价物是什么?它全部是 4 个字节,即 4294967295
。所以现在看起来像
if(15==4294967295) { /*its false */
/* some code */
}
由于 if
条件为 false,因此您的代码不会打印任何内容。
关于c - 整数如何提升为无符号整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50862644/