
By using a larger scope than is necessary, code becomes less readable and more likely to reference unintended variables. Minimizing scope requires that developers declare variables and functions where they will be used, improving maintainability.
Noncompliant Code Example (static
variables)
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
.
static int maximum; /* function finds max value in an array of ints */ public function findArrayMax(int *values){ ... if(values[i] > maximum){ maximum = values[i]; } ... }
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 operations.
/* 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]; } ... }
Noncompliant Code Example (for
-loop counters)
The counter variable i
is declared outside of the for
loop. This goes against this recommendation because it is not declared in the block in which it is used. If this snippet were reused with another index variable j
but there was a previously declared variable i
the loop could iterate over the wrong variable.
public void doStuff(...){ int i=0; for(i=0; i < 10; i++){ /* Perform Operations */ } }
Compliant Solution
Complying with this recommendation requires that you declare variables where they will be used, thus improving readability and reusability. In this example, this would be done by declaring the loop's index variable i
within the initialization of the for
loop. This was recently relaxed in the C99 standard.
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 |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
DCL19-C |
low |
unlikely |
medium |
P2 |
L3 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
[[ISO/IEC 9899:1999]] Appendix D.1.15, "Declaration in for
-Loop Statement"
DCL18-C. Beware integer constants beginning with 0 02. Declarations and Initialization (DCL)