From 5c2a2a5c2272b0b70e3b0d6b45bf361e384fb6a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Wed, 31 Dec 2014 15:14:22 +0100 Subject: [PATCH] Fixed #6095 (False positive oppositeInnerCondition - neglecting statements with side-effects) --- lib/checkcondition.cpp | 4 ++++ test/testcondition.cpp | 31 +++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/lib/checkcondition.cpp b/lib/checkcondition.cpp index 3e3eb2656..2beffb61e 100644 --- a/lib/checkcondition.cpp +++ b/lib/checkcondition.cpp @@ -426,6 +426,10 @@ void CheckCondition::oppositeInnerCondition() } if (Token::Match(tok->previous(), "++|--|& %var%")) break; + if (Token::Match(tok, "%var% . %var% (") && + !tok->variable()->isConst() && + !(tok->tokAt(2)->function() && tok->tokAt(2)->function()->isConst)) + break; if (Token::Match(tok->previous(), "[(,] %var% [,)]")) { // is variable unchanged? default is false.. bool unchanged = false; diff --git a/test/testcondition.cpp b/test/testcondition.cpp index bee2374fd..8ac0a8c8e 100644 --- a/test/testcondition.cpp +++ b/test/testcondition.cpp @@ -1062,6 +1062,37 @@ private: "}"); ASSERT_EQUALS("", errout.str()); + { + // #6095 - calling member function that might change the state + check("void f() {\n" + " const Fred fred;\n" // <- fred is const, warn + " if (fred.isValid()) {\n" + " fred.dostuff();\n" + " if (!fred.isValid()) {}\n" + " }\n" + "}"); + ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:5]: (warning) Opposite conditions in nested 'if' blocks lead to a dead code block.\n", errout.str()); + + check("class Fred { public: void dostuff() const; };\n" + "void f() {\n" + " Fred fred;\n" + " if (fred.isValid()) {\n" + " fred.dostuff();\n" // <- dostuff() is const, warn + " if (!fred.isValid()) {}\n" + " }\n" + "}"); + ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:6]: (warning) Opposite conditions in nested 'if' blocks lead to a dead code block.\n", errout.str()); + + check("void f() {\n" + " Fred fred;\n" + " if (fred.isValid()) {\n" + " fred.dostuff();\n" + " if (!fred.isValid()) {}\n" + " }\n" + "}"); + ASSERT_EQUALS("", errout.str()); + } + // #5731 - fp when undeclared variable is used check("void f() {\n" " if (x == -1){\n"