According to PC-lint, the following statement will never be TRUE:
if((variable & 0x02) == 1)
I am using a C compiler for embedded systems that evaluates it to TRUE whenever the corresponding bit in variable is set. I guess the compiler is doing a TRUE/FALSE comparison of both sides of the == instead of comparing the resulting numbers. In other words, every time the expression (varable & 0x02) is not zero (i.e. TRUE), the statement will also be TRUE, since the value 1 is also TRUE (not zero).
I don’t know if the C/C++ standards clearly define how a compiler should behave in this case. Are there any C/C++ experts out there who can answer this question based on what the standards (e.g. C90, C99, etc.) say?
P.S.: In the statement above, “variable” is an unsigned char.
PC-lint is right. Assuming
varis an integer variable, the expressionvar & 0x02can evaluate to two values:0and2. It will never be equal to1, which is what theifstatement is testing.To expand on this, the equality operator is being applied to two integer values. What matters is whether both operands evaluate to the same number, not whether they’re both simultaneously “true” or “false”.
To test whether bit 1 is set, one could use:
Given that your compiler behaves the way you say it does, it’s clearly non-compliant. However, it will almost certainly handle
if (variable & 0x02)correctly. My recommendation would be to fix the code so it won’t break silently if you were ever to change compilers.Finally, the situation is different if: (1) the code is C++ and not C; and (2)
variableis instance of a class; and (3) the class overloads the operators in question. In that case, the behaviour is down to what the overloaded operators actually do.