diff --git a/lib/checkother.cpp b/lib/checkother.cpp index 5cee5cf2a..b8488b17f 100644 --- a/lib/checkother.cpp +++ b/lib/checkother.cpp @@ -1734,6 +1734,9 @@ void CheckOther::checkVariableScope() if (!var || !var->isLocal() || (!var->isPointer() && !var->typeStartToken()->isStandardType() && !var->typeStartToken()->next()->isStandardType())) continue; + if (var->isConst()) + continue; + bool forHead = false; // Don't check variables declared in header of a for loop for (const Token* tok = var->typeStartToken(); tok; tok = tok->previous()) { if (tok->str() == "(") { @@ -1750,10 +1753,7 @@ void CheckOther::checkVariableScope() tok = tok->tokAt(3); if (!tok->isNumber() && tok->type() != Token::eString && tok->type() != Token::eChar && !tok->isBoolean()) continue; - } else if ((tok->str() == "=" || tok->str() == "(") && - ((!tok->next()->isNumber() && tok->next()->type() != Token::eString && tok->next()->type() != Token::eChar && !tok->next()->isBoolean()) || tok->strAt(2) != ";")) - continue; - + } bool reduce = true; bool used = false; // Don't warn about unused variables for (; tok != var->scope()->classEnd; tok = tok->next()) { diff --git a/test/testother.cpp b/test/testother.cpp index 2806bbc20..202d2682d 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -77,6 +77,7 @@ private: TEST_CASE(varScope17); TEST_CASE(varScope18); TEST_CASE(varScope19); // Ticket #4994 + TEST_CASE(varScope20); // Ticket #5103 TEST_CASE(oldStylePointerCast); TEST_CASE(invalidPointerCast); @@ -836,7 +837,7 @@ private: " for ( ; i < 10; ++i) ;\n" " }\n" "}"); - ASSERT_EQUALS("[test.cpp:2]: (style) The scope of the variable 'i' can be reduced.\n", errout.str()); + ASSERT_EQUALS("", errout.str()); varScope("void f(int x)\n" "{\n" @@ -985,7 +986,7 @@ private: " if (x == 5)\n" " foo(b);\n" "}"); - ASSERT_EQUALS("[test.cpp:2]: (style) The scope of the variable 'b' can be reduced.\n", errout.str()); + ASSERT_EQUALS("", errout.str()); varScope("void f(int x) {\n" " const bool b = x;\n" @@ -1167,6 +1168,16 @@ private: ASSERT_EQUALS("", errout.str()); } + void varScope20() { // Ticket #5103 - constant variable only used in inner scope + varScope("int f(int a) {\n" + " const int x = 234;\n" + " int b = a;\n" + " if (b > 32) b = x;\n" + " return b;\n" + "}"); + ASSERT_EQUALS("", errout.str()); + } + void checkOldStylePointerCast(const char code[]) { // Clear the error buffer.. errout.str("");