Weired char behavior in C++ / MSVC2005 / Windows 7 64 bit
I am using windows 7 64 bit开发者_开发问答 with MSVC2005 and QT (but I doubt QT is causing the problem since this is an issue with the fundamental data type char.
So when I try to compare two char's like so
char A=0xAA;
if(A==0xAA)
printf("Success");
else
printf("Fail");
lo and behold it fails! but when I do this
char A=0xAA;
char B=0xAA;
if(A==B)
printf("Success");
else
printf("Fail");
I get success! Actually when I thought about it... hey I'm working on a 64 bit processor.. even though char's are supposed to be treated as 1 byte. It's probablly stored as 4 bytes. So
char A=0xAA;
if(A==0xFFFFFFAA)
printf("Success");
else
printf("Fail");
Now I get success!!!
But WTF! Is this standard behavior!! If the damn thing is defined as a char, shouldn't the compiler know what to do with it? Further tests show that the extra bytes are only stored as one's if the most significant bit of the char is a 1. So 0x07 and lower is stored as 0x00000007. WTF.
Actually I seemed to have answered all my questions... except who to call to get this bug fixed. Is this even a bug? You can use MSVC2005 on 64 bit operating systems right or am I being an idiot. I guess I should get qt creator to use MSVC2010.. damn it. There goes my 2 hours.
You are comparing a (signed) char with the value -86 (256-0xAA) to an integer with the value 170 (0xAA).
The same will happen on a 32-bit system, and an 8-bit system, for that matter.
Not related to 64 bit: you need to define A as unsigned char to get correct behavior. Compiler warning shows that this code may be incorrect:
warning C4309: 'initializing' : truncation of constant value
精彩评论