Useless comparison test¶
ID: java/constant-comparisonKind: problemSecurity severity: Severity: warningPrecision: very-highTags: - quality - reliability - correctness - logic - external/cwe/cwe-570 - external/cwe/cwe-571Query suites: - java-security-and-quality.qls
Click to see the query in the CodeQL repository
The result of certain comparison tests can sometimes be inferred from their context and the results of other comparisons. This can be an indication of faulty logic and may result in dead code or infinite loops if, for example, a loop condition never changes its value.
Recommendation¶
Inspect the code to check whether the logic is correct, and consider simplifying the logical expression.
Example¶
In the following example the final test onx will always betrue, and thus the condition is redundant and potentially wrong. If the “do more stuff” part is intended to always execute after the loop then the condition should be removed to make this clear.
voidmethod(intx){while(x>=0){// do stuffx--;}if(x<0){// BAD: always true// do more stuff}}
References¶
Java Language Specification:The if Statement.
Common Weakness Enumeration:CWE-570.
Common Weakness Enumeration:CWE-571.