Inline constraint not respected
Non-const
static variable is modified in nonstatic inline
function
Description
This defect occurs when you refer to a file scope non-const
static
variable or define a local non-const
static variable in a nonstatic
inlined function.
For instance, var
is a non-const
static
variable defined in an inline
function
func
. g_step
is a file scope
non-const
static variable referred to in the same inlined
function.
static int g_step; inline void func (void) { static int var = 0; // Defect var += g_step; // Defect }
Risk
Modifying non-const
static variable in a nonstatic inline
function can result in unexpected and incorrect result. Consider an
extern
function func()
that you want to
use as an inlined function in file2.cpp
. A non-inline version of
the function is provided in file1.cpp
so that there is an
external definition of the function.
// file1.c void func(void) { static var1 = 0; var2 = 0; var1++; var2++; } |
// file2.c extern inline void func(void) { static var1 = 0; var2 = 0; var1++; var2++; } |
If func()
modified a
non-const
static variable, the behavior of the function is
unpredictable. If you call func()
, the compiler is allowed to
invoke either the inlined version or the non inlined version. See ISO®/IEC 9899:2011, sec. 6.7.4. It is possible that different calls to
func()
does not modify the same static variable
var1
. This behavior is unexpected can lead to incorrect
results.
Fix
Use one of these fixes:
If you do not intend to modify the variable, declare it as
const
.If you do not modify the variable, there is no question of unexpected modification.
Make the variable non-
static
. Remove thestatic
qualifier from the declaration.If the variable is defined in the function, it becomes a regular local variable. If defined at file scope, it becomes an extern variable.
Make the function
static
. Add astatic
qualifier to the function definition.If you make the function
static
, the file with the inlined definition always uses the inlined definition when the function is called. Other files use another definition of the function. The question of which function definition gets used is not left to the compiler.
Examples
Result Information
Group: Programming |
Language: C | C++ |
Default: On for handwritten code, off for generated code |
Command-Line Syntax:
INLINE_CONSTRAINT_NOT_RESPECTED |
Impact: Medium |
Version History
Introduced in R2018aSee Also
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)