类型转换反转

Typecasting Inversion

我真的不明白为什么我必须在之后对变量 b 进行类型转换 反转(一元 operator ~)。谁能解释为什么需要这个?

unsigned char a = 0xFF;
unsigned char b = 0x00; 

return (a == (~b));                //expected to return 1 but 0

...

return (a == (unsigned char)(~b)); //after typecast returns 1 as expected

~b 的结果属于提升类型 int(通常是 b 与任何其他一元运算符 +- 或 [=16 的结果=]) 所以你需要对结果进行类型转换。

来自 C11 规范草案第 6.5.3.3 节一元算术运算符:

The result of the ~ operator is the bitwise complement of its (promoted) operand (that is, each bit in the result is set if and only if the corresponding bit in the converted operand is not set). The integer promotions are performed on the operand, and the result has the promoted type. If the promoted type is an unsigned type, the expression ~E is equivalent to the maximum value representable in that type minus E.

所以,

unsigned char b = 0x00;
/* ~b = 0xFFFFFFFF (assuming 4 byte int), (unsigned char)~b = 0xFF */