Static local variable initialized with non-constant expression
(STALE_STATIC_LOCAL_VARIABLE)
R2026b Static const local variable initialized using parameter or local
variable
Since R2026b
Description
This defect occurs when a static const local variable is initialized
with a non-constant expression such as a function parameter, a local variable, or a data
member of a local object.
The checker applies to C++ code. In C, initializing a static variable
with a non-constant expression is a compilation error.
The checker also flags thread_local const local variables initialized
from parameters or local variables, because thread_local implies
static storage duration within each thread.
Risk
The static const variable silently retains its initial value from the
first function call. Callers that pass different arguments on subsequent calls observe
incorrect results because the variable does not update. This pattern is difficult to detect
in code reviews because the const qualifier suggests correctness and the
one-time initialization is not obvious from the function signature.
If the stale variable controls program logic, the defect can produce intermittent failures that depend on call order.
Fix
To fix this defect:
Remove the
statickeyword so the variable is reinitialized on each call.If the variable must persist across calls, remove the
constqualifier so it can be reassigned.If the variable is intended to capture the first-call value only, document this intent and justify the suppression.
If the variable is intended to be a
staticand aconst, intialize it using aconstexpr.If you do not want to fix the issue, add comments to your result or code to avoid another review.
Examples
Result Information
| Group: PROGRAMMING |
| Language: C++ |
| Impact: Medium |
Command-Line Syntax:
STALE_STATIC_LOCAL_VARIABLE |
PQL Name:
std.defects.STALE_STATIC_LOCAL_VARIABLE
|
Version History
Introduced in R2026b