From 35b6b2588ef1c74b2469a22dfd548f2253770a84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Fri, 12 Jun 2009 16:17:51 +0200 Subject: [PATCH] Fixed ticket #374 (False positive: The scope of variable can be limited) A few refactorings and fixes were made --- src/checkother.cpp | 15 +++++++++------ test/testother.cpp | 10 ++++++++++ 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/src/checkother.cpp b/src/checkother.cpp index 033962306..d42781abc 100644 --- a/src/checkother.cpp +++ b/src/checkother.cpp @@ -454,7 +454,6 @@ void CheckOther::CheckUnsignedDivision() // Check scope of variables.. //--------------------------------------------------------------------------- - void CheckOther::CheckVariableScope() { // Walk through all tokens.. @@ -526,8 +525,7 @@ void CheckOther::CheckVariableScope() continue; // Variable declaration? - if (Token::Match(tok1, "%var% %var% ;") || - Token::Match(tok1, "%var% %var% =")) + if (Token::Match(tok1, "%type% %var% [;=]")) { CheckVariableScope_LookupVar(tok1, tok1->strAt(1)); } @@ -550,7 +548,7 @@ void CheckOther::CheckVariableScope_LookupVar(const Token *tok1, const char varn int indentlevel = 0; int parlevel = 0; bool for_or_while = false; - while (indentlevel >= 0 && tok) + while (tok) { if (tok->str() == "{") { @@ -559,6 +557,8 @@ void CheckOther::CheckVariableScope_LookupVar(const Token *tok1, const char varn else if (tok->str() == "}") { + if (indentlevel == 0) + break; --indentlevel; if (indentlevel == 0) { @@ -603,8 +603,11 @@ void CheckOther::CheckVariableScope_LookupVar(const Token *tok1, const char varn tok = tok->next(); } - // Warning if "used" is true - variableScopeError(tok1, varname); + // Warning if this variable: + // * not used in this indentlevel + // * used in lower indentlevel + if (!used && used1) + variableScopeError(tok1, varname); } //--------------------------------------------------------------------------- diff --git a/test/testother.cpp b/test/testother.cpp index 83e7dc9a7..aeb349ece 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -54,6 +54,7 @@ private: TEST_CASE(varScope1); TEST_CASE(varScope2); TEST_CASE(varScope3); + TEST_CASE(varScope4); TEST_CASE(nullpointer1); TEST_CASE(nullpointer2); @@ -374,6 +375,15 @@ private: ASSERT_EQUALS("", errout.str()); } + void varScope4() + { + varScope("void foo()\n" + "{\n" + " int i;\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + } +