Main Content

MISRA C++:2023 Rule 6.7.1

Local variables shall not have static storage duration

Since R2024b

Description

Rule Definition

Local variables shall not have static storage duration.

Rationale

Multiple threads or functions can access objects with static storage duration simultaneously. Sharing access to local objects across functions can lead to multiple functions reading or writing the same object, resulting in data races and undefined behavior.

This rule does not apply to const or constexpr objects.

Polyspace Implementation

Polyspace® reports a violation of this rule if you declare a local object or a local anonymous union using the static keyword.

As an exception, Polyspace does not report violations of this rule if you declare local const and constexpr objects using these keywords.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

In this example, Polyspace reports a violation of this rule when you declare local objects using the static keyword.

int GLOBAL_COUNTER = 0;      // Compliant- static global object

class myClass
{
	static myClass &create() //static local function
	{
		static myClass app;   //Noncompliant
		return app;
	}
};

int myFunc(myClass a)
{
	int iterator = 0;          // Compliant
	static int static_counter = 0;   // Noncompliant
	static constexpr float PI = 3.1416;  // Compliant by exception- constexpr
	//...
}

As an exception, the constexpr local objects with static storage do not violate of this rule.

Check Information

Group: Basic Concepts
Category: Required

Version History

Introduced in R2024b