Why is this an issue?
Using the same value on either side of a binary operator is almost always a mistake. In the case of logical operators, it is either a copy/paste
error and therefore a bug, or it is simply wasted code, and should be simplified. In the case of bitwise operators and most binary mathematical
operators, having the same value on both sides of an operator yields predictable results, and should be simplified.
Noncompliant code example
if ( a == a ) { // always true
do_z();
}
if ( a != a ) { // always false
do_y();
}
if ( a == b && a == b ) { // if the first one is true, the second one is too
do_x();
}
if (a == b || a == b ) { // if the first one is true, the second one is too
do_w();
}
if (5 / 5) { // always 1
do_v();
}
if (5 - 5) { // always 0
do_u();
}
Exceptions
The following are ignored:
- The expression
1 << 1
- When an increment or decrement operator is used, ex:
*p++ == *p++
- Bitwise operators
|, &, ^
- Arithmetic operators
+, *
- Assignment operators
=, +=, *=
Resources
- CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
- {rule:cpp:S1656} - Implements a check on
=
.