Pages

Thursday, 16 July 2020

Why (unsigned char) -1 != -1 ?

Test Code


#include <stdio.h>

int main()
{
    unsigned char x = -1;
    if(x == -1){
        printf("Never run here");
    }else{
        printf("Gotcha!!\n");
    }
    return 0;
}


Why  (unsigned char) -1 != -1?


"(unsigned char) -1 " is 0xFF in memory, while -1 is 0xFFFF for 16bits int.

Before comparing, the C compiler will promote unsigned char to int as 0x00FF.

Now, 0x00FF != 0xFFFF



No comments:

Post a Comment