Home > Back-end >  C bit wise not operator changing values type?
C bit wise not operator changing values type?

Time:02-20

I was testing some C code and ran into an error that threw me for a loop. I ended up creating the following code as a test and the results surprised me.

It appears as though the ~ operator is somehow changing the interpretation of the value (i.e. Its type), because unless type casted the test fails. Any insight as to what is going on is appreciated.

Code:

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;
}

Output:

One: 65534 Two: 1
Test: Fail
Test: Pass
Test: Fail

CodePudding user response:

unsigned int one = 1;
~one; // This expression has type int. So it's likely to be 0xFFFFFFFE
  • Related