Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This noncompliant code example shows a variable that is declared outside the for loop. This reduces reusability because the value of the loop index i will have changed after the for statement. Consider, for instance, the case when this code snippet is copied and pasted with the intent to use a different index j. If index variable change is omitted, the new loop would then attempt to iterate over index i. Unexpected behavior may can follow because i remains in scope.

...

Minimize the scope of variables where possible, for example, by declaring loop indexes within the for statement.

...

Detecting local variables that are declared in a larger scope than is required by the as-written code is straightforward , and can avoid any possibility of false positives.

Detecting multiple for statements that use the same index variable is straightforward; it will produce false positives in the unusual case where this was intended by the programmer.

Other Languages

Related Guidelines

This guideline appears in the C Secure Coding Standard as : DCL19-C. Use as minimal a scope as possible for all variables and functions.

This guideline appears in the C++ Secure Coding Standard as : DCL07-CPP. Use as minimal scope as possible for all variables and methods.

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this guideline on the CERT website.

Bibliography

Wiki Markup
\[[Bloch 2001|AA. Bibliography#Bloch 01]\] Item 29, Minimize the scope of local variables
\[[JLS 2005|AA. Bibliography#JLS 05]\] [Section 14.4.2, Scope of Local Variable Declarations|http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.4.2]

...