Why is this an issue?
Bitwise operations are operations that manipulate individual bits in binary representations of numbers. These operations work at the binary level,
treating numbers as sequences of 32 bits (in 32-bit environments) or 64 bits (in 64-bit environments). However, they should not be used in a boolean
context because they have different behaviors compared to logical operators when applied to boolean values:
- When applied to boolean values, bitwise AND (
&
) and OR (|
) perform bitwise operations on the binary
representation of the numbers. They treat the operands as 32-bit signed integers and manipulate their individual bits.
- Logical AND (
&&
) and OR (||
) are specifically designed for boolean operations. They return a boolean value
based on the truthiness or falsiness of the operands.&&
returns true
if both operands are truthy; otherwise, it
returns false
. ||
operator returns true
if at least one of the operands is truthy; otherwise, it returns
false
.
Bitwise operators &
and |
can be easily mistaken for logical operators &&
and ||
,
especially for those who are not familiar with the distinction between them or their specific use cases.
This rule raises an issue when &
or |
is used in a boolean context.
if (a & b) { /* ... */ } // Noncompliant: The operator & is used in a boolean context
You should use the logical variant of the bitwise operator, that is, &&
instead of &
and ||
instead of |
.
if (a && b) { /* ... */ }
Exceptions
When a file contains other bitwise operations, (^
, <<
, >>>
, >>
,
~
, &=
, ^=
, |=
, <<=
, >>=
, >>>=
, and
&
or |
used with a numeric literal as the right operand) all issues in the file are ignored, because it is evidence that
bitwise operations were truly intended.
Resources
Documentation