diff --git a/lib/valueflow.cpp b/lib/valueflow.cpp index cae64e52d..a6ea2761a 100644 --- a/lib/valueflow.cpp +++ b/lib/valueflow.cpp @@ -3844,6 +3844,13 @@ const Token* ValueFlow::getEndOfExprScope(const Token* tok, const Scope* default const Token* varEnd = getEndOfVarScope(var); if (!end || (smallest ? precedes(varEnd, end) : succeeds(varEnd, end))) end = varEnd; + + const Token* top = var->nameToken()->astTop(); + if (top && Token::simpleMatch(top->tokAt(-1), "if (")) { // variable declared in if (...) + const Token* elseTok = top->link()->linkAt(1); + if (Token::simpleMatch(elseTok, "} else {") && tok->scope()->isNestedIn(elseTok->tokAt(2)->scope())) + end = tok->scope()->bodyEnd; + } } } return ChildrenToVisit::op1_and_op2; diff --git a/test/testunusedvar.cpp b/test/testunusedvar.cpp index 181445bd0..527fb5c19 100644 --- a/test/testunusedvar.cpp +++ b/test/testunusedvar.cpp @@ -5446,6 +5446,37 @@ private: " return y;\n" "}"); ASSERT_EQUALS("", errout.str()); + + functionVariableUsage("int f(int i) {\n" // #11788 + " if (int x = i) {\n" + " return x;\n" + " }\n" + " else {\n" + " x = 12;\n" + " return x;\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + + functionVariableUsage("void f(int i) {\n" + " if (int x = i) {\n" + " while (x < 100) {\n" + " if (x % 2 == 0) {\n" + " x += 3;\n" + " }\n" + " else if (x % 3 == 0) {\n" + " x += 5;\n" + " }\n" + " else {\n" + " x += 7;\n" + " }\n" + " x += 6;\n" + " }\n" + " return x;\n" + " }\n" + " return i;\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); } void localvarOpAssign() {