diff --git a/lib/checkother.cpp b/lib/checkother.cpp index 4aaa887d7f0..cf5ecb65b91 100644 --- a/lib/checkother.cpp +++ b/lib/checkother.cpp @@ -1292,7 +1292,7 @@ void CheckOther::checkVariableScope() tok = tok->link(); // parse else if blocks.. - } else if (Token::simpleMatch(tok, "else { if (") && Token::simpleMatch(tok->linkAt(3), ") {")) { + } else if (Token::simpleMatch(tok, "else { if (") && tok->next()->isSimplifiedScope() && Token::simpleMatch(tok->linkAt(3), ") {")) { tok = tok->next(); } else if (tok->varId() == var->declarationId() || tok->str() == "goto") { reduce = false; diff --git a/lib/tokenize.cpp b/lib/tokenize.cpp index d0e46b54542..bb3957fb9ae 100644 --- a/lib/tokenize.cpp +++ b/lib/tokenize.cpp @@ -7964,8 +7964,8 @@ void Tokenizer::elseif() if (Token::Match(tok2, "}|;")) { if (tok2->next() && tok2->strAt(1) != "else") { - tok->insertToken("{"); - tok2->insertToken("}"); + tok->insertToken("{")->isSimplifiedScope(true); + tok2->insertToken("}")->isSimplifiedScope(true); Token::createMutualLinks(tok->next(), tok2->next()); break; } diff --git a/test/testother.cpp b/test/testother.cpp index 0ccd482c353..06512a930c9 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -122,6 +122,7 @@ class TestOther : public TestFixture { TEST_CASE(varScope42); TEST_CASE(varScope43); TEST_CASE(varScope44); + TEST_CASE(varScope45); TEST_CASE(oldStylePointerCast); TEST_CASE(intToPointerCast); @@ -1972,6 +1973,17 @@ class TestOther : public TestFixture { errout_str()); } + void varScope45() { + check("void g(int x, int y) {\n" // #14497 + " int a = x, b = y;\n" + " if (a) {}\n" + " else {\n" + " if (b) {}\n" + " }\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:2:16]: (style) The scope of the variable 'b' can be reduced. [variableScope]\n", errout_str()); + } + #define checkOldStylePointerCast(...) checkOldStylePointerCast_(__FILE__, __LINE__, __VA_ARGS__) template void checkOldStylePointerCast_(const char* file, int line, const char (&code)[size], Standards::cppstd_t std = Standards::CPPLatest) {