diff --git a/lib/checkother.cpp b/lib/checkother.cpp index c49a1f6d8..866191ae1 100644 --- a/lib/checkother.cpp +++ b/lib/checkother.cpp @@ -1548,7 +1548,9 @@ void CheckOther::checkConstPointer() continue; if (!tok->variable()->isLocal() && !tok->variable()->isArgument()) continue; - if (tok == tok->variable()->nameToken()) + const Token* const nameTok = tok->variable()->nameToken(); + // declarations of (static) pointers are (not) split up, array declarations are never split up + if (tok == nameTok && (!Token::simpleMatch(tok->variable()->typeStartToken()->previous(), "static") || Token::simpleMatch(nameTok->next(), "["))) continue; if (!tok->valueType()) continue; @@ -1561,7 +1563,7 @@ void CheckOther::checkConstPointer() bool deref = false; if (parent && parent->isUnaryOp("*")) deref = true; - else if (Token::simpleMatch(parent, "[") && parent->astOperand1() == tok) + else if (Token::simpleMatch(parent, "[") && parent->astOperand1() == tok && parent->astOperand1() != nameTok) deref = true; if (deref) { if (Token::Match(parent->astParent(), "%cop%") && !parent->astParent()->isUnaryOp("&") && !parent->astParent()->isUnaryOp("*")) @@ -1593,7 +1595,7 @@ void CheckOther::checkConstPointer() if (nonConstPointers.find(p) == nonConstPointers.end()) { const Token *start = (p->isArgument()) ? p->scope()->bodyStart : p->nameToken()->next(); const int indirect = p->isArray() ? p->dimensions().size() : 1; - if (p->isStatic() || isVariableChanged(start, p->scope()->bodyEnd, indirect, p->declarationId(), false, mSettings, mTokenizer->isCPP())) + if (isVariableChanged(start, p->scope()->bodyEnd, indirect, p->declarationId(), false, mSettings, mTokenizer->isCPP())) continue; constVariableError(p, nullptr); } diff --git a/test/testother.cpp b/test/testother.cpp index d863bbe75..8e800d79e 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -2974,11 +2974,24 @@ private: // #10744 check("S& f() {\n" - " static S * p = new S();\n" + " static S* p = new S();\n" " return *p;\n" "}\n"); ASSERT_EQUALS("", errout.str()); + check("int f() {\n" + " static int i[1] = {};\n" + " return i[0];\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'i' can be declared with const\n", errout.str()); + + check("int f() {\n" + " static int i[] = { 0 };\n" + " int j = i[0] + 1;\n" + " return j;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'i' can be declared with const\n", errout.str()); + // #10471 check("void f(std::array const& i) {\n" " if (i[0] == 0) {}\n"