This raises an issue when code performs a bitwise AND operation with the literal value 0, as the result is always 0
regardless of the other operand.
A bitwise AND operation combines two values bit by bit. When one of the operands is 0, every bit in the result will be 0 because 0 AND anything is always 0. This makes the operation meaningless and any subsequent comparison trivial.
For example, an expression that checks whether the result of ANDing a value with 0 equals 0 will always evaluate to true, and an expression checking whether that result differs from 0 will always evaluate to false, regardless of what the value contains.
This pattern almost always indicates a programming error. Common mistakes include:
Since the operation produces a predictable result that doesn’t depend on the actual value being tested, it serves no useful purpose and should be corrected.
This bug can lead to incorrect program behavior because conditions that should vary based on runtime values become constant:
The appropriate fix depends on the root cause:
0 with the intended bitmask value. For example, use a hexadecimal constant like
0x01 or a named constant that represents the bit positions you meant to test.& operator with the operator you actually intended, such as == for
equality comparison, % for modulo, or | for bitwise OR.
int flags = getFlags();
if ((flags & 0) == 0) { // Noncompliant
// This block always executes
doSomething();
}
int flags = getFlags();
if ((flags & 0x01) == 0) {
// Now this checks if the least significant bit is not set
doSomething();
}