Skip to content

Commit d7313f3

Browse files
committed
C/C++ : Useless test
1 parent bb2feda commit d7313f3

File tree

3 files changed

+78
-0
lines changed

3 files changed

+78
-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: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<!DOCTYPE qhelp PUBLIC
2+
"-//Semmle//qhelp//EN"
3+
"qhelp.dtd">
4+
<qhelp>
5+
6+
<overview>
7+
<p>Comparisons operation like <code>a==8 && a!=7</code> contains an useless part : the non-equal part. This rule finds any test of this kind within an if or a while statement
8+
This rule will only find useless comparisons with a right literal operand. </p>
9+
</overview>
10+
11+
<recommendation>
12+
<p>Remove the useless comparisons</p>
13+
</recommendation>
14+
15+
<example>
16+
<sample src="UselessTest.cpp" />
17+
</example>
18+
19+
</qhelp>
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* @name Useless Test
3+
* @description Find any useless test of kind a==8 && a!=7
4+
* @kind problem
5+
* @problem.severity warning
6+
* @id cpp/uselesstest
7+
* @tags reliability
8+
* readability
9+
*/
10+
11+
import cpp
12+
13+
predicate sameStmt(Expr e1, Expr e2) {
14+
e1.getNumChild() = e2.getNumChild() and
15+
e1.toString() = e2.toString() and
16+
(
17+
e1.getNumChild() = 0
18+
or
19+
forall(int i | i in [0 .. e1.getNumChild() - 1] | sameStmt(e1.getChild(i), e2.getChild(i)))
20+
)
21+
}
22+
23+
Element nearestParent(Expr e) {
24+
if
25+
e.getParent().(Expr).getFullyConverted() instanceof ParenthesisExpr or
26+
e.getParent() instanceof IfStmt or
27+
e.getParent() instanceof WhileStmt
28+
then result = e.getParent()
29+
else result = nearestParent(e.getParent())
30+
}
31+
32+
from LogicalAndExpr b, EQExpr eq, NEExpr ne
33+
where
34+
(
35+
b.getAChild*() = eq and
36+
b.getAChild*() = ne and
37+
eq.getParent() instanceof LogicalAndExpr and
38+
ne.getParent() instanceof LogicalAndExpr
39+
) and
40+
(
41+
eq.getChild(0) instanceof VariableAccess and ne.getChild(0) instanceof VariableAccess
42+
or
43+
eq.getChild(0) instanceof PointerDereferenceExpr and
44+
ne.getChild(0) instanceof PointerDereferenceExpr
45+
) and
46+
eq.getChild(1) instanceof Literal and
47+
ne.getChild(1) instanceof Literal and
48+
nearestParent(eq) = nearestParent(ne) and
49+
sameStmt(eq.getChild(0), ne.getChild(0))
50+
select "Useless test", ne

0 commit comments

Comments
 (0)