I have the following loop in C++, compiled with g++ 4.1.2:
while(1) {
int status = getStatus();
bool firstOk = status & 0x1;
bool secondOk = status & 0x2;
if(firstOk != m_firstOk) {
logStatus(1, firstOk);
m_firstOk = firstOk;
}
if(secondOk != m_secondOk) {
logStatus(2, secondOk);
m_secondOk = secondOk;
}
sleep(1);
}
Note logStatus() receives its parameters by value, so the parameter is not modified. m_firstOk and m_secondOk are of course bool member attributes.
This was working fine until now. I received a report that it didn't detect when firstOk changed. I attached to the running process with gdb. It was in the sleep() line and I got astonished when I saw the following:
(gdb) p m_firstOk
$1 = true
(gdb) p m_secondOk
$2 = true
(gdb) p firstOk
$3 = 244
WTF? How can firstOk be 244 when it should be the result of a bitwise AND with 0x1? I know a boolean is in fact stored as an integer, but how could my bitwise AND be ignored? Since it's 244, it's being evaluated as true when it should be false, which is the cause of the problem.
Isn't assigning the result of a bitwise AND to a boolean safe? Is this a gcc bug? Or should I do something like the following?
bool firstOk = (status & 0x1) ? true : false;
Thanks in advance.