Fixed #272 ("The scope of the variable XXX can be limited" not detected when variable is initilialized during declaration)

http://sourceforge.net/apps/trac/cppcheck/ticket/272
This commit is contained in:
Slava Semushin 2009-08-17 02:12:57 +07:00
parent 32c8ba526b
commit 74bbe945f6
2 changed files with 25 additions and 1 deletions

View File

@ -591,7 +591,19 @@ void CheckOther::checkVariableScope()
continue;
// Variable declaration?
if (Token::Match(tok1, "%type% %var% [;=]"))
if (Token::Match(tok1, "%type% %var% ; %var% = %any% ;"))
{
// Tokenizer modify "int i = 0;" to "int i; i = 0;",
// so to handle this situation we just skip
// initialization (see ticket #272).
const unsigned int firstVarId = tok1->next()->varId();
const unsigned int secondVarId = tok1->tokAt(3)->varId();
if (firstVarId > 0 && firstVarId == secondVarId)
{
lookupVar(tok1->tokAt(6), tok1->strAt(1));
}
}
else if (Token::Match(tok1, "%type% %var% [;=]"))
{
lookupVar(tok1, tok1->strAt(1));
}

View File

@ -55,6 +55,7 @@ private:
TEST_CASE(varScope2);
TEST_CASE(varScope3);
TEST_CASE(varScope4);
TEST_CASE(varScope5);
TEST_CASE(nullpointer1);
TEST_CASE(nullpointer2);
@ -405,6 +406,17 @@ private:
ASSERT_EQUALS("", errout.str());
}
void varScope5()
{
varScope("void f)\n"
"{\n"
" int i = 0;\n"
" if (true) {\n"
" for ( ; i < 10; ++i) ;\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) The scope of the variable i can be limited\n", errout.str());
}