Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C bit wise not operator changing values type?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading