by tlb · 11y ago · 0 comments
bool foo = rx&0x0800; // set foo if 11th bit of rx is true
which works in C++ or if you have stdbool, but not if you have 'typedef char bool' which occurs in header files of projects that should know better. bool foo = (rx & 0x0800) == 0x0800;
Not only does this not have the bug, it communicates your intent better, and modern compilers are quite capable of optimizing this.Here's a snippet from an open source 8051 simulator that I was debugging today:
if( ((RAM[ACC] & 0xF0) >> 4) > 9 ||
GetBit(RAM[PSW], CY) == 0x01 ) {
tempAdd = RAM[ACC] + 0x60;
RAM[ACC] = tempAdd;
if( ((unsigned char*)&tempAdd)[1] != 0 ) {
SetBit(RAM[PSW], CY);
}
}
The code is supposed to set the carry flag when RAM[ACC] + 0x60 overflows into two bytes. Can you spot the bug? It involves my favorite C++ feature: implicit conversions, and my second favorite feature: signed chars.The bug is that when RAM[ACC] is something like 0xFF, it gets cast to (int) -1 so the the upper byte and hence the carry flag never get set.
I predict there's lots more more evil that can milked from this fount.