diff --git a/lib/checkother.cpp b/lib/checkother.cpp index 12995eaab..920b058b5 100644 --- a/lib/checkother.cpp +++ b/lib/checkother.cpp @@ -867,6 +867,16 @@ void CheckOther::checkVariableScope() if (var->isConst()) continue; + // reference of range for loop variable.. + if (Token::Match(var->nameToken()->previous(), "& %var% = %var% .")) { + const Token *otherVarToken = var->nameToken()->tokAt(2); + const Variable *otherVar = otherVarToken->variable(); + if (otherVar && Token::Match(otherVar->nameToken(), "%var% :") && + otherVar->nameToken()->next()->astParent() && + Token::Match(otherVar->nameToken()->next()->astParent()->previous(), "for (")) + 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() == "(") { diff --git a/test/testother.cpp b/test/testother.cpp index b7aab0507..560da47cc 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -85,6 +85,7 @@ private: TEST_CASE(varScope23); // Ticket #6154 TEST_CASE(varScope24); // pointer / reference TEST_CASE(varScope25); // time_t + TEST_CASE(varScope26); // range for loop, map TEST_CASE(oldStylePointerCast); TEST_CASE(invalidPointerCast); @@ -1190,6 +1191,19 @@ private: "}", "test.c"); ASSERT_EQUALS("[test.c:2]: (style) The scope of the variable 'currtime' can be reduced.\n", errout.str()); } + + void varScope26() { + check("void f(const std::map &m) {\n" + " for (auto it : m) {\n" + " if (cond1) {\n" + " int& key = it.first;\n" + " if (cond2) { dostuff(key); }\n" + " }\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + } + void checkOldStylePointerCast(const char code[]) { // Clear the error buffer.. errout.str("");