From fa067724d71b5192ec2ae16b5d8749d6118129ef Mon Sep 17 00:00:00 2001 From: "ouyang.wei.victor" Date: Mon, 24 Aug 2026 18:05:50 +0800 Subject: [PATCH] Detect uninitvar when variable is used as ternary condition isVariableUsage() did not treat a variable appearing as the condition of a ternary operator as a read, because '?' is an eExtendedOp token and is therefore rejected by Token::isOp(). The scope analysis then assumed the variable was assigned and stopped, so `x = flag ? 10 : 0;` was silently accepted while `if (flag)` was correctly reported. Fixes #90 --- samples/cpp/uninitvar.cpp | 11 +++++++++++ trunk/lib/checkuninitvar.cpp | 4 ++++ 2 files changed, 15 insertions(+) diff --git a/samples/cpp/uninitvar.cpp b/samples/cpp/uninitvar.cpp index 9337b85..45b79b0 100644 --- a/samples/cpp/uninitvar.cpp +++ b/samples/cpp/uninitvar.cpp @@ -7,4 +7,15 @@ void Demo(int b) } // 缺少else分支,变量a可能不会初始化 a++; +} + +unsigned short TernaryDemo(unsigned short input) +{ + unsigned char flag; + if (input > 0) + { + flag = 1; + } + // 三目运算符的条件会读取变量flag + return flag ? 10 : 0; } \ No newline at end of file diff --git a/trunk/lib/checkuninitvar.cpp b/trunk/lib/checkuninitvar.cpp index 4f42bff..b760e97 100644 --- a/trunk/lib/checkuninitvar.cpp +++ b/trunk/lib/checkuninitvar.cpp @@ -781,6 +781,10 @@ int CheckUninitVar::isVariableUsage(const Token *vartok, bool pointer, Alloc all return (var && var->typeStartToken()->isStandardType()); } + const Token *parent = vartok->astParent(); + if (alloc == NO_ALLOC && Token::simpleMatch(parent, "?") && parent->astOperand1() == vartok) + return true; + if (alloc == NO_ALLOC && vartok->next() && vartok->next()->isOp() && !vartok->next()->isAssignmentOp()) return true;