Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Adding an NCCE/CS pair discussing for loop variable declaration hiding.

...

By using different variable names globally and locally, the compiler forces the developer to be more precise and descriptive with variable names.

Noncompliant Code Example

This noncompliant code example declares two variables with the same identifier, but in slightly different scopes. The scope of the identifier i declared in the for loop's initial clause terminates after the closing curly brace of the for loop. The scope of the identifier i declared in the for loop's compound statement terminates before the closing curly brace. Thus, the inner declaration of i hides the outer declaration of i, which can lead to unintentionally referencing the wrong object.

Code Block
bgColor#FFCCCC
langc
void f(void) {
  for (int i = 0; i < 10; i++) {
    long i;
    /* ... */
  }
}

Compliant Solution

This compliant solution uses a unique identifier for the variable declared within the for loop.

Code Block
bgColor#ccccff
langc
void f(void) {
  for (int i = 0; i < 10; i++) {
    long j;
    /* ... */
  }
}

Exceptions

DCL01-EX1: A function argument in a function declaration may clash with a variable in a containing scope provided that when the function is defined, the argument has a name that clashes with no variables in any containing scopes.

...