diff --git a/lib/checkuninitvar.cpp b/lib/checkuninitvar.cpp index 960a22016..6817fdbf1 100644 --- a/lib/checkuninitvar.cpp +++ b/lib/checkuninitvar.cpp @@ -1241,7 +1241,7 @@ bool CheckUninitVar::checkScopeForVariable(const Scope* scope, const Token *tok, return true; std::map varValueIf; - if (!initif && !noreturnIf) { + if (!alwaysFalse && !initif && !noreturnIf) { for (const Token *tok2 = tok; tok2 && tok2 != tok->link(); tok2 = tok2->next()) { if (Token::Match(tok2, "[;{}.] %var% = - %var% ;")) varValueIf[tok2->next()->varId()] = NOT_ZERO; @@ -1268,10 +1268,10 @@ bool CheckUninitVar::checkScopeForVariable(const Scope* scope, const Token *tok, bool possibleInitElse(number_of_if > 0 || suppressErrors); bool noreturnElse = false; - const bool initelse = checkScopeForVariable(scope, tok->next(), var, &possibleInitElse, NULL, membervar); + const bool initelse = !alwaysTrue && checkScopeForVariable(scope, tok->next(), var, &possibleInitElse, NULL, membervar); std::map varValueElse; - if (!initelse && !noreturnElse) { + if (!alwaysTrue && !initelse && !noreturnElse) { for (const Token *tok2 = tok; tok2 && tok2 != tok->link(); tok2 = tok2->next()) { if (Token::Match(tok2, "[;{}.] %var% = - %var% ;")) varValueElse[tok2->next()->varId()] = NOT_ZERO; @@ -1286,10 +1286,8 @@ bool CheckUninitVar::checkScopeForVariable(const Scope* scope, const Token *tok, // goto the } tok = tok->link(); - if (initif && initelse) - return true; - - if ((initif && noreturnElse) || (initelse && noreturnIf)) + if ((alwaysFalse || initif || noreturnIf) && + (alwaysTrue || initelse || noreturnElse)) return true; if ((initif || initelse || possibleInitElse) && !noreturnIf && !noreturnElse) { diff --git a/test/testuninitvar.cpp b/test/testuninitvar.cpp index dfa6b30b2..72e39d612 100644 --- a/test/testuninitvar.cpp +++ b/test/testuninitvar.cpp @@ -2261,11 +2261,41 @@ private: "}"); ASSERT_EQUALS("", errout.str()); - checkUninitVar2("int* f(int a) {\n" // #4560 + checkUninitVar2("int f(int a) {\n" // #4560 " int x = 0, y;\n" " if (a) x = 1;\n" " else return 0;\n" " if (x) y = 123;\n" // <- y is always initialized + " else {}\n" + " return y;\n" + "}"); + ASSERT_EQUALS("", errout.str()); + + checkUninitVar2("int f(int a) {\n" // #4560 + " int x = 1, y;\n" + " if (a) x = 0;\n" + " else return 0;\n" + " if (x) {}\n" + " else y = 123;\n" // <- y is always initialized + " return y;\n" + "}"); + ASSERT_EQUALS("", errout.str()); + + checkUninitVar2("static int x;" // #4773 + "int f() {\n" + " int y;\n" + " if (x) g();\n" + " if (x) y = 123;\n" + " else y = 456;\n" + " return y;\n" + "}"); + ASSERT_EQUALS("", errout.str()); + + checkUninitVar2("static int x;" // #4773 + "int f() {\n" + " int y;\n" + " if (!x) g();\n" + " if (x) y = 123;\n" " else y = 456;\n" " return y;\n" "}");