C 位明智不是运算符更改值类型?
C bit wise not operator changing values type?
我正在测试一些 C 代码,运行 遇到了一个错误,让我陷入了循环。我最终创建了以下代码作为测试,结果让我感到惊讶。
似乎 ~ 运算符以某种方式改变了值的解释(即它的类型),因为除非类型强制转换,否则测试失败。对正在发生的事情的任何见解表示赞赏。
代码:
int main()
{
unsigned short one=1, two=1, three=1;
one=~one;
printf("One: %hu Two: %hu\n",one,two);
printf("Test: %s\n",(one==~three)? "Pass": "Fail");
printf("Test: %s\n",(one==(unsigned short)~three)? "Pass": "Fail");
printf("Test: %s\n",(one==~(unsigned short)three)? "Pass": "Fail");
return 0;
}
输出:
One: 65534 Two: 1
Test: Fail
Test: Pass
Test: Fail
unsigned int one = 1;
~one; // This expression has type int. So it's likely to be 0xFFFFFFFE
我正在测试一些 C 代码,运行 遇到了一个错误,让我陷入了循环。我最终创建了以下代码作为测试,结果让我感到惊讶。
似乎 ~ 运算符以某种方式改变了值的解释(即它的类型),因为除非类型强制转换,否则测试失败。对正在发生的事情的任何见解表示赞赏。
代码:
int main()
{
unsigned short one=1, two=1, three=1;
one=~one;
printf("One: %hu Two: %hu\n",one,two);
printf("Test: %s\n",(one==~three)? "Pass": "Fail");
printf("Test: %s\n",(one==(unsigned short)~three)? "Pass": "Fail");
printf("Test: %s\n",(one==~(unsigned short)three)? "Pass": "Fail");
return 0;
}
输出:
One: 65534 Two: 1
Test: Fail
Test: Pass
Test: Fail
unsigned int one = 1;
~one; // This expression has type int. So it's likely to be 0xFFFFFFFE