From 724c78fb4d28c6ddccad444e7c68d37604daf184 Mon Sep 17 00:00:00 2001 From: Reijo Tomperi Date: Wed, 30 Sep 2009 00:56:43 +0300 Subject: [PATCH] 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 --- src/checkother.cpp | 13 ++++++++++++- test/testother.cpp | 42 ++++++++++++++++++++++++++++++++++++++---- 2 files changed, 50 insertions(+), 5 deletions(-) diff --git a/src/checkother.cpp b/src/checkother.cpp index 13551ac81..e6aee4968 100644 --- a/src/checkother.cpp +++ b/src/checkother.cpp @@ -644,8 +644,19 @@ void CheckOther::lookupVar(const Token *tok1, const char varname[]) 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; + if (parlevel == 0 && (tok->str() == ";")) for_or_while = false; } diff --git a/test/testother.cpp b/test/testother.cpp index 92023d475..8b67a3ee3 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -517,10 +517,20 @@ private: void varScope5() { - varScope("void f()\n" + varScope("void f(int x)\n" "{\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" " }\n" "}\n"); @@ -540,10 +550,34 @@ private: " }\n" "}\n"); ASSERT_EQUALS("", errout.str()); + + varScope("void f()\n" + "{\n" + "int foo = 0;\n" + "std::vector 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[]) { // Tokenize..