Monday, August 24, 2009

Puzzler #1


unsigned char x = 0x80;

main (void) {
char y;

y = 0x80;
if (x != y) {
printf("This should not happen\n");
}
}


Why does the string "This should not happen" appear on the console? It does on VS2005 for x86, but may not on a 8051 processor.

Answer: The problem is that 'char' and 'unsigned char' are different when it comes to comparisons, and that compilers like to optimize the comparison using machine register sizes. C casts the operands to machine sizes: unsigned char 0x80 gets cast to 0x00000080, and signed char 0x80 gets cast to 0xFFFFFF80. Then when you compare them, they don't equate! ARGH....

No comments: