Skip to content

Commit 3597d80

Browse files
authored
Merge pull request #7787 from Yonah125/main
C/C++ : Useless test
2 parents 5828a61 + a59a9ba commit 3597d80

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
void test(){
2+
int a = 8;
3+
int b = 9;
4+
5+
//Useless NonEquals
6+
if(a==8 && a != 7) {}
7+
8+
while(a==8 && a!=7){}
9+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<!DOCTYPE qhelp PUBLIC
2+
"-//Semmle//qhelp//EN"
3+
"qhelp.dtd">
4+
<qhelp>
5+
6+
<overview>
7+
<p>Comparison operations like <code>a==8 &amp;&amp; a!=7</code> contain a useless part : the non-equal part. This rule finds tests of this kind within an <code>if</code> or a <code>while</code> statement</p>
8+
</overview>
9+
10+
<recommendation>
11+
<p>Remove the useless comparisons</p>
12+
</recommendation>
13+
14+
<example>
15+
<sample src="UselessTest.cpp" />
16+
</example>
17+
18+
</qhelp>
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* @name Useless Test
3+
* @description A boolean condition that is guaranteed to never be evaluated should be deleted.
4+
* @kind problem
5+
* @problem.severity warning
6+
* @id cpp/uselesstest
7+
* @tags reliability
8+
* readability
9+
*/
10+
11+
import cpp
12+
import semmle.code.cpp.valuenumbering.GlobalValueNumbering
13+
14+
predicate sameExpr(Expr e1, Expr e2) { globalValueNumber(e1).getAnExpr() = e2 }
15+
16+
Element nearestParent(Expr e) {
17+
if
18+
e.getParent().(Expr).getConversion*() instanceof ParenthesisExpr or
19+
e.getParent() instanceof IfStmt or
20+
e.getParent() instanceof WhileStmt
21+
then result = e.getParent()
22+
else result = nearestParent(e.getParent())
23+
}
24+
25+
from LogicalAndExpr b, EQExpr eq, NEExpr ne
26+
where
27+
(
28+
b.getAChild*() = eq and
29+
b.getAChild*() = ne and
30+
eq.getParent() instanceof LogicalAndExpr and
31+
ne.getParent() instanceof LogicalAndExpr
32+
) and
33+
(
34+
eq.getLeftOperand() instanceof VariableAccess and ne.getLeftOperand() instanceof VariableAccess
35+
or
36+
eq.getLeftOperand() instanceof PointerDereferenceExpr and
37+
ne.getLeftOperand() instanceof PointerDereferenceExpr
38+
) and
39+
eq.getRightOperand() instanceof Literal and
40+
ne.getRightOperand() instanceof Literal and
41+
nearestParent(eq) = nearestParent(ne) and
42+
sameExpr(eq.getLeftOperand(), ne.getLeftOperand())
43+
select ne, "Useless Test"

0 commit comments

Comments
 (0)