Why is some of my code being skipped?
My program is exhibiting some odd behavior when I step through it in the debugger. In the following excerpt, it checks pktNum != ~invPktNum
and then proceeds directly the the second return 1;
statement.
The debugger shows that pktNum
is an unsigned char that is 0x01 and invPktNum
is an unsigned char that is 0xFE.
/* Verify message integrity. */
if (pktNum != ~invPktNum) {
return 1;
}
ccrc = crc16_ccitt(msg, XModem_Blo开发者_JAVA百科ck_Size);
if ( (((ccrc>>8) & 0xFF) != crcBuf[0])
|| ((ccrc & 0xFF) != crcBuf[1]) ) {
return 1;
}
The compiler has folded the two return 1
cases into the exact same code. Both if
tests branch to the same assembly instruction. Each instruction can only be tagged with a single line number for the debugger, so you see that strange behavior. If you compile with -g
and without -O
(or even more explicitly use -O0
) it will make distinct cases and things will be more clear.
Unary !
is logical-NOT. If the operand is 0
the result is 1
, otherwise the result is 0
. This means that !invPktNum
is 0
, so the if
expression is true.
You are probably looking for unary ~
, which is bitwise-NOT.
By the way, it may appear in a debugger as if the second return 1;
is being executed rather than the first, because the compiler may have reordered the code and combined those two return 1;
statements together (particularly if optimisation is enabled).
!(0xFE)
is 0
. Maybe what you wanted was ~(0xFE)
?
Check compiler optimizations are definitely disabled for debug mode. (Just to be different to everybody else)
You're comparing an int to a bool. That's bad style to begin with, and some compilers will complain.
Maybe you mixed up !
and ~
? !invPktNum
will return false if invPktNum is non-false, and true if it's false. I'm pretty sure you meant ~invPktNum
.
精彩评论