diff --git a/lib/checkunusedvar.cpp b/lib/checkunusedvar.cpp index 7c60c29d8..2c3d5c19b 100644 --- a/lib/checkunusedvar.cpp +++ b/lib/checkunusedvar.cpp @@ -1337,14 +1337,21 @@ void CheckUnusedVar::checkFunctionVariableUsage() else if (!usage._write && !usage._allocateMemory && var && !var->isStlType() && !isEmptyType(var->type())) unassignedVariableError(usage._var->nameToken(), varname); else if (!usage._var->isMaybeUnused() && !usage._modified && !usage._read && var) { - if (usage._lastAccess->linenr() == var->nameToken()->linenr() && var->nameToken()->next()->isSplittedVarDeclEq()) { - bool error = true; + const Token* vnt = var->nameToken(); + bool error = false; + if (vnt->next()->isSplittedVarDeclEq()) { + const Token* nextStmt = vnt->tokAt(2); + while (nextStmt && nextStmt->str() != ";") + nextStmt = nextStmt->next(); + error = precedes(usage._lastAccess, nextStmt); + } + if (error) { if (mTokenizer->isCPP() && var->isClass() && (!var->valueType() || var->valueType()->type == ValueType::Type::UNKNOWN_TYPE)) { const std::string typeName = var->getTypeName(); switch (mSettings->library.getTypeCheck("unusedvar", typeName)) { case Library::TypeCheck::def: - reportLibraryCfgError(var->nameToken(), typeName); + reportLibraryCfgError(vnt, typeName); break; case Library::TypeCheck::check: break; @@ -1353,7 +1360,7 @@ void CheckUnusedVar::checkFunctionVariableUsage() } } if (error) - unreadVariableError(usage._var->nameToken(), varname, false); + unreadVariableError(vnt, varname, false); } } } diff --git a/test/testunusedvar.cpp b/test/testunusedvar.cpp index 3fc87062a..9c2921313 100644 --- a/test/testunusedvar.cpp +++ b/test/testunusedvar.cpp @@ -3333,8 +3333,8 @@ private: ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'var' is assigned a value that is never used.\n", errout.str()); } - void localvar62() { // #10824 - functionVariableUsage("void f() {\n" + void localvar62() { + functionVariableUsage("void f() {\n" // #10824 " S* s = nullptr;\n" "}\n"); ASSERT_EQUALS("[test.cpp:2]: (style) Variable 's' is assigned a value that is never used.\n", errout.str()); @@ -3343,6 +3343,23 @@ private: " S* s{};\n" "}\n"); TODO_ASSERT_EQUALS("[test.cpp:2]: (style) Variable 's' is assigned a value that is never used.\n", "", errout.str()); + + functionVariableUsage("int f() {\n" + " int i = 0, j = 1;\n" + " return i;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'j' is assigned a value that is never used.\n", errout.str()); + + functionVariableUsage("int f() {\n" + " int i = 0, j = 1;\n" + " return j;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'i' is assigned a value that is never used.\n", errout.str()); + + functionVariableUsage("void f() {\n" // #10846 + " int i = 1; while (i) { i = g(); }\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); } void localvarloops() {