Why is this an issue?
If a boolean expression doesn’t change the evaluation of the condition, then it is entirely unnecessary, and can be removed. If it is gratuitous
because it does not match the programmer’s intent, then it’s a bug and the expression should be fixed.
Noncompliant code example
a = true;
if (a) { // Noncompliant
doSomething();
}
if (b && a) { // Noncompliant; "a" is always "true"
doSomething();
}
if (c || !a) { // Noncompliant; "!a" is always "false"
doSomething();
}
Compliant solution
a = true;
if (foo(a)) {
doSomething();
}
if (b) {
doSomething();
}
if (c) {
doSomething();
}
Resources
- MISRA C:2004, 13.7 - Boolean operations whose results are invariant shall not be permitted.
- MISRA C:2012, 14.3 - Controlling expressions shall not be invariant
- MITRE, CWE-571 - Expression is Always True
- MITRE, CWE-570 - Expression is Always False
- CERT, MSC12-C. - Detect and remove code that has no effect or is never executed