Fix #750 (cppcheck wants variable outside do-loop to be only inside loop)

http://sourceforge.net/apps/trac/cppcheck/ticket/750
Fix #758 (False positive on variable scope with boost foreach)
http://sourceforge.net/apps/trac/cppcheck/ticket/758
This commit is contained in:
Reijo Tomperi 2009-09-30 00:56:43 +03:00
parent 9d9d600d43
commit 724c78fb4d
2 changed files with 50 additions and 5 deletions

View File

@ -644,8 +644,19 @@ void CheckOther::lookupVar(const Token *tok1, const char varname[])
else if (indentlevel == 0) else if (indentlevel == 0)
{ {
if ((tok->str() == "for") || (tok->str() == "while")) // %unknown% ( %any% ) {
// If %unknown% is anything except if, we assume
// that it is a for or while loop or a macro hiding either one
if (Token::simpleMatch(tok->next(), "(") &&
Token::simpleMatch(tok->next()->link()->next(), "{"))
{
if (tok->str() != "if")
for_or_while = true;
}
if (Token::simpleMatch(tok, "do {"))
for_or_while = true; for_or_while = true;
if (parlevel == 0 && (tok->str() == ";")) if (parlevel == 0 && (tok->str() == ";"))
for_or_while = false; for_or_while = false;
} }

View File

@ -517,10 +517,20 @@ private:
void varScope5() void varScope5()
{ {
varScope("void f()\n" varScope("void f(int x)\n"
"{\n" "{\n"
" int i = 0;\n" " int i = 0;\n"
" if (true) {\n" " if (x) {\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());
varScope("void f(int x)\n"
"{\n"
" int i = 0;\n"
" if (x) {b()}\n"
" else {\n"
" for ( ; i < 10; ++i) ;\n" " for ( ; i < 10; ++i) ;\n"
" }\n" " }\n"
"}\n"); "}\n");
@ -540,10 +550,34 @@ private:
" }\n" " }\n"
"}\n"); "}\n");
ASSERT_EQUALS("", errout.str()); ASSERT_EQUALS("", errout.str());
varScope("void f()\n"
"{\n"
"int foo = 0;\n"
"std::vector<int> vec(10);\n"
"BOOST_FOREACH(int& i, vec)\n"
"{\n"
" foo += 1;\n"
" if(foo == 10)\n"
" {\n"
" return 0;\n"
" }\n"
"}\n"
"}\n");
ASSERT_EQUALS("", errout.str());
varScope("void f(int &x)\n"
"{\n"
" int n = 1;\n"
" do\n"
" {\n"
" ++n;\n"
" ++x;\n"
" } while (x);\n"
"}\n");
ASSERT_EQUALS("", errout.str());
} }
void checkNullPointer(const char code[]) void checkNullPointer(const char code[])
{ {
// Tokenize.. // Tokenize..