c - Unsigned integer 和 unsigned char 保持相同的值但表现不同为什么?

标签 c

为什么会这样

unsigned char k=-1
if(k==-1)

是假的

unsigned int k=-1
if(k==-1)

是真的

最佳答案

为了演示,我们假设 8 位 char 和 32 位 int

unsigned char k=-1;

k 被赋值为 255。

if(k==-1)

== 运算符的左侧是一个unsigned char。右边是一个int。由于 unsigned char 的所有可能值都可以放入 int 中,因此左侧被转换为 int(这是由于整数促销,在下面引用)。这导致比较 (255 == -1),这是错误的。


unsigned int k=-1

k 被赋值为 4294967295

if(k==-1)

这一次,左边(一个无符号整数)不能放在一个整数中。该标准表示,在这种情况下,两个值都将转换为无符号整数。所以这导致比较 (4294967295 == 4294967295),这是真的。


标准中的相关引述:

整数提升:(C99,6.3.1.1p2)

If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int.

通常的算术转换:(6.3.1.8)。

[For integral operands, ] the integer promotions are performed on both operands. Then the following rules are applied to the promoted operands:
- If both operands have the same type, then no further conversion is needed.
...
- Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
...

关于c - Unsigned integer 和 unsigned char 保持相同的值但表现不同为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16771890/

相关文章:

c - libssh 绑定(bind)_接受错误 : Could not create BIO

c - 这个程序最后是怎么得到5的呢?

c - 有没有办法接收各种数据类型?

c - 使用 for 循环以 X 模式打印字符

c - 在 C 中解析命令行参数

c++ - 无缝滚动瓦片 map

c - 尝试使用 strtok() 作为 C 中的 shell 函数

c - 使用 ntohs 的无符号整数

c - 如何在 linux 中从/proc/cpuinfo 获取模型名称?

c - ARM架构下调用函数的GCC返回地址