Variable scope: Fix FP for reference variable in range for loop

This commit is contained in:
Daniel Marjamäki 2019-04-02 12:59:24 +02:00
parent 6b9a25869e
commit 3f9dd4c567
2 changed files with 24 additions and 0 deletions

View File

@ -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() == "(") {

View File

@ -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<int,int> &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("");