Skip to content

Commit b908bb1

Browse files
committed
Fixed #5503 (FP: Uninitialized variable - initialize in in if and else branch)
1 parent 923f7f8 commit b908bb1

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

lib/checkuninitvar.cpp

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,14 @@ static void conditionAlwaysTrueOrFalse(const Token *tok, const std::map<unsigned
205205
}
206206

207207
else if (tok->isComparisonOp()) {
208+
if (tok->values.size() == 1U && tok->values.front().isKnown()) {
209+
if (tok->values.front().intvalue)
210+
*alwaysTrue = true;
211+
else
212+
*alwaysFalse = true;
213+
return;
214+
}
215+
208216
const Token *vartok, *numtok;
209217
if (tok->astOperand2() && tok->astOperand2()->isNumber()) {
210218
vartok = tok->astOperand1();
@@ -404,7 +412,7 @@ bool CheckUninitVar::checkScopeForVariable(const Token *tok, const Variable& var
404412
return true;
405413
}
406414

407-
if (alwaysTrue && noreturnIf)
415+
if (alwaysTrue && (initif || noreturnIf))
408416
return true;
409417

410418
std::map<unsigned int, VariableValue> varValueIf;

test/testuninitvar.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -778,6 +778,17 @@ class TestUninitVar : public TestFixture {
778778
"}");
779779
ASSERT_EQUALS("", errout.str());
780780

781+
checkUninitVar("int foo(int x)\n" // #5503
782+
"{\n"
783+
" int i;\n"
784+
" if (x < 2)\n"
785+
" i = 22;\n"
786+
" else if (x >= 2)\n" // condition is always true
787+
" i = 33;\n"
788+
" return i;\n"
789+
"}");
790+
ASSERT_EQUALS("", errout.str());
791+
781792
checkUninitVar("int foo()\n"
782793
"{\n"
783794
" int i;\n"

0 commit comments

Comments
 (0)