Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions lib/valueflow.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7924,10 +7924,24 @@ static Token* findStartToken(const Variable* var, Token* start, const Library* l
Token* first = uses.front();
if (Token::findmatch(start, "goto|asm|setjmp|longjmp", first))
return start;
const Scope* scope = first->scope();
// If there is only one usage or the first usage is in the same scope
if (uses.size() == 1 || scope == var->scope())
// If there is only one usage
if (uses.size() == 1)
return first->previous();
const Scope* scope = first->scope();
// If first usage is in variable scope
if (scope == var->scope()) {
bool isLoopExpression = false;
for (const Token* parent = first; parent; parent = parent->astParent()) {
if (Token::simpleMatch(parent->astParent(), ";") &&
Token::simpleMatch(parent->astParent()->astParent(), ";") &&
Token::simpleMatch(parent->astParent()->astParent()->astParent(), "(") &&
Token::simpleMatch(parent->astParent()->astParent()->astParent()->astOperand1(), "for (") &&
parent == parent->astParent()->astParent()->astParent()->astOperand2()->astOperand2()->astOperand2()) {
isLoopExpression = true;
}
}
return isLoopExpression ? start : first->previous();
}
// If all uses are in the same scope
if (std::all_of(uses.begin() + 1, uses.end(), [&](const Token* tok) {
return tok->scope() == scope;
Expand Down
13 changes: 11 additions & 2 deletions test/testvalueflow.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5392,7 +5392,7 @@ class TestValueFlow : public TestFixture {
" int c;\n"
" if (d)\n"
" c = 0;\n"
" else if (e)\n"
" else if (e)\n"
" c = 0;\n"
" c++;\n"
"}\n";
Expand All @@ -5406,7 +5406,7 @@ class TestValueFlow : public TestFixture {
" int c;\n"
" if (d)\n"
" c = 0;\n"
" else if (!d)\n"
" else if (!d)\n"
" c = 0;\n"
" c++;\n"
"}\n";
Expand Down Expand Up @@ -5510,6 +5510,15 @@ class TestValueFlow : public TestFixture {
"}\n";
values = tokenValues(code, "i ++", ValueFlow::Value::ValueType::UNINIT);
ASSERT_EQUALS(0, values.size());

// #11688
code = "void f() {\n"
" int n;\n"
" for (int i = 0; i < 4; i = n)\n" // <- n is initialized in the loop body
" n = 10;\n"
"}";
values = tokenValues(code, "n )", ValueFlow::Value::ValueType::UNINIT);
ASSERT_EQUALS(0, values.size());
}

void valueFlowConditionExpressions() {
Expand Down