
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
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
Compiling your program with the -std=c99
flag will detect this usage. By default, some compilers do not operate in C99 mode. As declaring integers in for
loop initialization was a recent addition to C99, following this recommendation may cause a compile error if an older standard is used.
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"