This rule raises an issue when a bitwise operation (& or |) is used in a comparison where the bit mask and compared
value are incompatible, making the comparison always true or always false regardless of the input.
When performing bitwise operations in comparisons, the relationship between the bit mask and the compared value determines what results are possible. If this relationship makes certain outcomes impossible, the comparison becomes a constant expression.
For bitwise AND operations (&), the result can only have bits set where the mask has bits set. For example, x & 1
can only produce values 0 or 1, never 2. Comparing this result to an impossible value like 2 creates dead code.
For bitwise OR operations (|), the result always includes all bits set in the mask. If the compared value doesn’t include all mask
bits, the comparison can never be equal.
These constant comparisons indicate logical errors in the code. They waste processing time on checks that always have the same outcome, create confusion for developers reading the code, and may indicate incomplete or incorrect implementation of bit flag checking logic. In security-sensitive contexts, such errors might bypass intended validation checks.
The impact depends on the context where the faulty comparison appears:
Review the bit mask and comparison value to ensure they are logically compatible. For AND operations, verify that the compared value only has bits that exist in the mask. For OR operations, verify that the compared value includes all bits from the mask.
int x = getUserPermissions();
if ((x & 1) == 2) { // Noncompliant
grantAccess();
}
int x = getUserPermissions();
if ((x & 2) == 2) {
grantAccess();
}