Gratuitous boolean expressions are conditions that do not change the evaluation of a program. This issue can indicate logical errors and affect the
correctness of an application, as well as its maintainability.
Why is this an issue?
Control flow constructs like if
-statements allow the programmer to direct the flow of a program depending on a boolean expression.
However, if the condition is always true or always false, only one of the branches will ever be executed. In that case, the control flow construct and
the condition no longer serve a purpose; they become gratuitous.
What is the potential impact?
The presence of gratuitous conditions can indicate a logical error. For example, the programmer intended to have the program branch into
different paths but made a mistake when formulating the branching condition. In this case, this issue might result in a bug and thus affect the
reliability of the application. For instance, it might lead to the computation of incorrect results.
Additionally, gratuitous conditions and control flow constructs introduce unnecessary complexity. The source code becomes harder to understand, and
thus, the application becomes more difficult to maintain.
How to fix it
Gratuitous boolean expressions are suspicious and should be carefully removed from the code.
First, the boolean expression in question should be closely inspected for logical errors. If a mistake was made, it can be corrected so the
condition is no longer gratuitous.
If it becomes apparent that the condition is actually unnecessary, it can be removed. The associated control flow construct (e.g., the
if
-statement containing the condition) will be adapted or even removed, leaving only the necessary branches.
Code examples
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