The use of bool
operands with other operators is unlikely to be meaningful (or intended). Best case it will be confusing to
maintainers, worst case it will not have the intended effect. Either way, it is highly recommended to stick to boolean operators when dealing with
bool
operands.
This rule allows the detection of such uses, which often occur because the logical operators (&&
, ||
and
!
) can be easily confused with the bitwise operators (&
, |
and ~
).
Noncompliant code example
bool b1 = true;
bool b2 = false;
int8_t s8a;
if ( b1 & b2 ) // Noncompliant
if ( ~b1 ) // Noncompliant
if ( b1 < b2 ) // Noncompliant
if ( b1 ^ b2 ) // Noncompliant
Compliant solution
if ( b1 && b2 )
if ( !b1 )
if ( b1 == false )
if ( b1 == b2 )
if ( b1 != b2 )
s8a = b1 ? 3 : 7;
Exceptions
Operators |=
and &=
are ignored when used with bool
operands. Operator ++
is also ignored
with a bool
operand because it is covered by rule S2668.
void test(bool b1, bool b2, int i1) {
b1 |= b2; // ignored
b1++; // ignored here, handled by S2668
b1 &= b2; // ignored
b1 &= i1; // Noncompliant; right operand is not a bool
}