Skip to content

Commit

Permalink
Fixed danmar#4155 (false positive: Variable is assigned a value that …
Browse files Browse the repository at this point in the history
…is never used (inside BOOST_FOREACH loop))
  • Loading branch information
danmar committed Dec 17, 2012
1 parent a84d21f commit 72ea94b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/checkunusedvar.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -746,6 +746,14 @@ void CheckUnusedVar::checkFunctionVariableUsage_iterateScopes(const Scope* const
break;
}

if (Token::Match(tok,"%var% (") && Token::simpleMatch(tok->linkAt(1),") {") && !Token::Match(tok, "for|while|if|catch")) {
const Token * const endTok = tok->linkAt(1)->linkAt(1);
for (const Token *tok2 = endTok->link(); tok2 && tok2 != endTok; tok2 = tok2->next()) {
if (tok2->varId())
variables.erase(tok2->varId());
}
}

if (Token::Match(tok->previous(), "[;{}]")) {
for (const Token* tok2 = tok->next(); tok2; tok2 = tok2->next()) {
if (tok2->varId()) {
Expand Down
13 changes: 13 additions & 0 deletions test/testunusedvar.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ class TestUnusedVar : public TestFixture {
TEST_CASE(localvarIfElse); // return tmp1 ? tmp2 : tmp3;
TEST_CASE(localvarOpAssign); // a |= b;
TEST_CASE(localvarFor); // for ( ; var; )
TEST_CASE(localvarForEach); // BOOST_FOREACH, hlist_for_each, etc
TEST_CASE(localvarShift1); // 1 >> var
TEST_CASE(localvarShift2); // x = x >> 1
TEST_CASE(localvarShift3); // x << y
Expand Down Expand Up @@ -2948,6 +2949,18 @@ class TestUnusedVar : public TestFixture {
ASSERT_EQUALS("", errout.str());
}

void localvarForEach() {
functionVariableUsage("void foo() {\n"
" int i = -1;\n"
" int a[] = {1,2,3};\n"
" FOREACH_X (int x, a) {\n"
" if (i==x) return x;\n"
" i = x;\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout.str());
}

void localvarShift1() {
functionVariableUsage("int foo()\n"
"{\n"
Expand Down

0 comments on commit 72ea94b

Please sign in to comment.