Variables and functions should be declared in the minimum scope from which all references to the identifier are still possible.
When a By using a larger scope than necessary is necessaryused, code becomes less readable, harder to maintain, and more likely to reference unintended variables . Minimizing scope requires that developers declare variables and functions where they will be used, improving maintainability(see DCL01-C. Do not reuse variable names in subscopes).
Noncompliant Code Example
...
In this noncompliant code example, the function counter() increments the global variable count and then returns immediately if this variable exceeds a maximum value:The variable maximum is declared as a static variable outside of the function findArrayMax although it is not necessary. Thus, maximum may not be properly initialized and findArrayMax may not work as intended if called more than once. Additionally, if any other part of the program modifies maximum then it may cause faulty behavior in findArrayMax.
| Code Block | ||||
|---|---|---|---|---|
| ||||
unsignedstatic int count maximum= 0; /* function finds max value in an array of ints */ public function findArrayMax(int *values)void counter() { ... if(values[i]if (count++ > maximumMAX_COUNT){ maximum = values[i] return; } /* ... */ } |
Assuming that the variable count is only accessed from this function, this example is noncompliant because it does not define count within the minimum possible scope.
Compliant Solution
The maximum variable's scope is only in the function that uses it. As a result, it is properly initialized each time the function is called. This also removes the possibility that another part of the program can modify the variable and alter the function's operationsIn this compliant solution, the variable count is declared within the scope of the counter() function as a static variable. The static modifier, when applied to a local variable (one inside of a function), modifies the lifetime (duration) of the variable so that it persists for as long as the program does and does not disappear between invocations of the function.
| Code Block | ||
|---|---|---|
| ||
/* function finds max value in an array of ints */
public function findArrayMax(int *values){
int maximum = INT_MIN;
...
if(values[i] > maximum){
maximum = values[i];
}
...
}
|
...
| |||
void counter() {
static unsigned int count = 0;
if (count++ > MAX_COUNT) return;
/* ... */
}
|
The keyword static also prevents reinitialization of the variable.
Noncompliant Code Example
The counter variable i is declared outside of the for loop. This , which goes against this recommendation because it is not declared in the block in which it is used. If this snippet this code were reused with another index variable j, but there was a previously declared variable i, the loop could iterate over the wrong variable.
| Code Block | ||||
|---|---|---|---|---|
| ||||
size_t i = public void doStuff(...){ int i=0; for for(i=0; i < 10; i++){ /* Perform Operationsoperations */ } } |
Compliant Solution
Complying with this recommendation requires that you declare variables where they will be are used, thus improving which improves readability and reusability. In this example, this would be done by declaring the you would declare the loop's index variable i within the initialization of the for loop. This requirement was recently relaxed in the C99 standardC Standard.
| Code Block | ||||
|---|---|---|---|---|
| ||||
for (size_t i=0; i < 10; i++) {
/* Perform operations */
}
|
Noncompliant Code Example (Function Declaration)
In this noncompliant code example, the function f() is called only from within the function g(), which is defined in the same compilation unit. By default, function declarations are extern, meaning that these functions are placed in the global symbol table and are available from other compilation units.
| Code Block | ||||
|---|---|---|---|---|
| ||||
int f(int i) {
/* Function definition */
}
int g(int i) {
int j = f(i);
/* ... */
} |
Compliant Solution
In this compliant solution, the function f() is declared with internal linkage. This practice limits the scope of the function declaration to the current compilation unit and prevents the function from being included in the external symbol table. It also limits cluttering in the global name space and prevents the function from being accidentally or intentionally invoked from another compilation unit. See DCL15-C. Declare file-scope objects or functions that do not need external linkage as static for more information.
| Code Block | ||||
|---|---|---|---|---|
| ||||
static int f(int i) { /* Function definition */ } int g(int i) { int j = f(i); /* ... */ } public void doStuff(...){ for(int i=0; i < 10; i++){ /* Perform Operations */ } } |
Risk Assessment
Failure to minimize scope could result in less reliable, readable, and reusable code.
Recommendation | Severity | Likelihood |
|---|
Detectable | Repairable | Priority | Level |
|---|---|---|---|
DCL19-C | Low |
Unlikely |
Yes |
Yes |
P3 | L3 |
Automated Detection
...
Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
| Astrée |
| local-object-scope global-object-scope | Partially checked | ||||||
| Axivion Bauhaus Suite |
| CertC-DCL19 | |||||||
| CodeSonar |
| LANG.STRUCT.SCOPE.FILE | Scope could be file static | ||||||
| CC2.DCL19 | Fully implemented | |||||||
| Helix QAC |
| C1504, C1505, C1531, C1532, C3210, C3218 | |||||||
| Klocwork |
| MISRA.VAR.MIN.VIS | |||||||
| LDRA tool suite |
| 25 D, 61 D, 40 S | Fully implemented | ||||||
| Parasoft C/C++test |
| CERT_C-DCL19-a | Declare variables as locally as possible | ||||||
| PC-lint Plus |
| 765, 9003 | Partially supported | ||||||
| Polyspace Bug Finder |
| Checks for:
Rec. partially covered. | |||||||
| PVS-Studio |
| V821 | |||||||
| RuleChecker |
| local-object-scope global-object-scope | Partially checked |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
| Wiki Markup |
|---|
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Appendix D.1.15, "Declaration in {{for}}\-Loop Statement" |
Related Guidelines
| SEI CERT C++ Coding Standard | VOID DCL07-CPP. Minimize the scope of variables and methods |
| MISRA C:2012 | Rule 8.9 (advisory) |
...