Main Content

Number of local static variables exceeds threshold

The number of local static variables in a function is greater than the defined threshold

Since R2021a

Description

This defect is raised on a function when the number of local static variables in the function is greater than the defined checker threshold. For details about how Polyspace calculates the number of local static variables in a function, see Number of Local Static Variables.

Polyspace® uses the default threshold 20 unless you specify a threshold. To specify a selection file where you can set the threshold, use the option Set checkers by file (-checkers-selection-file) or Checkers activation file (-checkers-activation-file).

When you import comments from previous analyses by using polyspace-comments-import, Polyspace copies any review information on the code metric Number of Local Static Variables in the previous result to this checker in the current result. If the current result contains the same code metric, the review information is copied to the code metric as well.

Risk

The content of a static variable might be influenced by many different ways. When your function has too many static variables, it indicates that the data in your code is not properly encapsulated and your functions might have unexpected interdependencies. These factor make your code difficult to test and maintain, and might introduce bugs that are difficult to diagnose.

Fix

To fix this check, either refactor your code or change the checker threshold. When refactoring your code:

  • Encapsulate and modularize independent data or code.

  • Communicate between functions by using local variables instead of global or static variables.

A best practice is to check the complexity of a module early in development to avoid costly post-development refactoring.

Examples

expand all

void foo(void){//Noncompliant
	
	static int a;
	static int b;
	static int c;
	static int d;
	static int e;
	static int f;
	static int g;
	//...
}

In this example, the function foo has seven local static variables, which is more than the specified threshold of five. Polyspace flags the function.

Correction — Encapsulate Related Data

One possible correction is to encapsulate related data in structures or classes. In this code, the related integer variables are encapsulated into a structure. The function foo now contains only one static copy of the structure..

typedef struct {
	int a;
	int b;
	int c;
	int d;
	int e;
	int f;
	int g;
} data_vars;
void foo(void){//Compliant
	
	static data_vars A;
	//...
}

Check Information

Group: Software Complexity
Language: C | C++
Acronym: SC09
Default Threshold: 20

Version History

Introduced in R2021a