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 () takes its parameters by value, so the parameter does not change. m_firstOk and m_secondOk are, of course, bool member attributes.
This has worked so far. I got a message that it did not detect when firstOk changed. I connected to the running process using gdb. This was in the sleep () line, and I was surprised to see 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 bitwise AND with 0x1? I know that a boolean is actually stored as an integer, but how is it bitwise AND ignored? Since it is 244, it is judged to be true when it must be false, which is the cause of the problem.
Doesn't assign a bitwise AND logical safe result? Is this a gcc error? Or do I need to do something like the following?
bool firstOk = (status & 0x1) ? true : false;
Thanks in advance.
source share