Skip to content

Commit 8cd680b

Browse files
Fix #8862 Enhancement: false negative: variablescope (#6294)
1 parent 82fcffa commit 8cd680b

2 files changed

Lines changed: 27 additions & 0 deletions

File tree

lib/checkother.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -915,6 +915,10 @@ static bool isSimpleExpr(const Token* tok, const Variable* var, const Settings*
915915
if (Token::Match(ftok, "%name% (") &&
916916
((ftok->function() && ftok->function()->isConst()) || settings->library.isFunctionConst(ftok->str(), /*pure*/ true)))
917917
needsCheck = true;
918+
if (tok->isArithmeticalOp() &&
919+
(!tok->astOperand1() || isSimpleExpr(tok->astOperand1(), var, settings)) &&
920+
(!tok->astOperand2() || isSimpleExpr(tok->astOperand2(), var, settings)))
921+
return true;
918922
}
919923
return (needsCheck && !findExpressionChanged(tok, tok->astParent(), var->scope()->bodyEnd, settings));
920924
}

test/testother.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,7 @@ class TestOther : public TestFixture {
100100
TEST_CASE(varScope37); // #12158
101101
TEST_CASE(varScope38);
102102
TEST_CASE(varScope39);
103+
TEST_CASE(varScope40);
103104

104105
TEST_CASE(oldStylePointerCast);
105106
TEST_CASE(invalidPointerCast);
@@ -1710,6 +1711,28 @@ class TestOther : public TestFixture {
17101711
ASSERT_EQUALS("", errout_str());
17111712
}
17121713

1714+
void varScope40() {
1715+
checkP("#define NUM (-999.9)\n"
1716+
"double f(int i) {\n"
1717+
" double a = NUM;\n"
1718+
" double b = -NUM;\n"
1719+
" double c = -1.0 * NUM;\n"
1720+
" if (i == 1) {\n"
1721+
" return a;\n"
1722+
" }\n"
1723+
" if (i == 2) {\n"
1724+
" return b;\n"
1725+
" }\n"
1726+
" if (i == 3) {\n"
1727+
" return c;\n"
1728+
" }\n"
1729+
" return 0.0;\n"
1730+
"}\n");
1731+
ASSERT_EQUALS("[test.cpp:3]: (style) The scope of the variable 'a' can be reduced.\n"
1732+
"[test.cpp:4]: (style) The scope of the variable 'b' can be reduced.\n"
1733+
"[test.cpp:5]: (style) The scope of the variable 'c' can be reduced.\n",
1734+
errout_str());
1735+
}
17131736

17141737
#define checkOldStylePointerCast(code) checkOldStylePointerCast_(code, __FILE__, __LINE__)
17151738
void checkOldStylePointerCast_(const char code[], const char* file, int line) {

0 commit comments

Comments
 (0)