9

Here is my problem code:

#include "stdio.h"

int main()
{
        char a = -1;
        unsigned char b = 255;
        unsigned char c = 0;
        if((~a) ==  c)
                printf("OK 1");
        else
                printf("bad 1");
        printf("\n");
        if((~b) ==  c)
                printf("OK 2");
        else
                printf("bad 2");
        printf("\n");
}

I expected this to print:

OK 1

OK 2

But, I get OK 1 and bad 2!

If unsigned char b is 255 (11111111), then ~b should be 00000000. Why does it not equal c?

I work on Linux SUSE, using gcc.

4

2 回答 2

12

你被整数促销所困扰。当你这样做时:

~b == c

b并且c都晋升为int. 这意味着你真的在做:

~0x000000ff == 0

最终比较:

0xffffff00 == 0

哪个不匹配。它适用于您的第一种情况,因为您的char类型已签名,并在促销中得到扩展:

~a == c
~(-1) == 0
~0xffffffff == 0
0 == 0
于 2013-07-25T22:39:38.627 回答
2

由于标准的积分提升:在表达式~b中,操作数被提升为int,可能类似于0x000000FF; 结果是整数0xFFFFFF00

您必须将结果转换回unsigned char

if ((unsigned char)(~b) == c) /* ... */
于 2013-07-25T22:40:20.090 回答