Versions Compared

Key

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

Do not use the same variable name in two scopes where one scope is contained in another.   Example Examples include:

  • No other variable should share the name of a global variable
  • A block should not declare a vairable the same name as a variable declared in any block that contains it.

Reusing variable names leads to programmer confusion about which variable is being modified.   Additionally, if variable names are reused, generally one or both of the variable names are too generic.

Non-compliant Code Example 1

In the following example, the programmer sets the value of the msg variable expecting to reuse that outside the block. Due to the reuse of the same variable name, however, the outside msg variable value is not changed.

Code Block
char msg[100];
{
      char msg[80] = "Hello";
      strcpy(msg, "Error");
}

printf ("%s\n", msg);

Exceptions

 When When the block is small, although still not desirable, the danger of reusing variable names is mitigated by the visibility of the immediate declaration.

References