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. Examples includeFor example,

  • No other variable should share the name of a global variable if the other value variable is in a subscope of the global variable.
  • A block should not declare a variable with 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.

...

Noncompliant Code Example

This non-compliant noncompliant code example declares the msg identifier at the start of the compilation unit (with file scope ) and reuses the same identifier to declare a character array local to the report_error() function. Consequently, the The programmer unintentionally copies a string may unintentionally copy the function argument to the locally declared msg array within the report_error() function, failing . Depending on the programmer's intention, it either fails to initialize the assign global variable and resulting in a potential buffer overflow msg or allows the local msg buffer to overflow by using the global value msgsize as a bounds for the local buffer.

Code Block
bgColor#FFCCCC
langc
#include <stdio.h>
 
static char msg[100];
static const size_t msgsize = sizeof( msg);

void report_error(const char const *error_msgstr) {
  char msg[80];
  snprintf(msg, msgsize, "Error: %s\n", str);
  /* ... */
}

int main(void) {
  /* ... */
  strncpy(msg, error_msg, sizeof(msg));
report_error("some error");
 
  return 0;
}

Compliant Solution

This compliant solution uses different, more descriptive variable names:

Code Block
bgColor#ccccff
langc
#include <stdio.h>
 

int main(voidstatic char message[100];
static const size_t message_size = sizeof( message);

void report_error(const char *str) {
  char error_msg[80];
  snprintf(msg, sizeof( msg), "Error: %s\n", str);
  /* Ensure error_msg isn't too long ... */
}

int main(void) {
  /* ... */
  report_error("some error");
 
  return 0;
}

When the block is small, the danger of reusing variable names is mitigated by the visibility of the immediate declaration. Even in this case, however, variable name reuse is not desirable. In general, the larger the declarative region of an identifier, the more descriptive and verbose should be the name of the identifier.

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)if (strlen(error_msg) >= sizeof(msg)) {
  for  error_msg[sizeof(error_msg) - 1] = '\0';
  }
  report_error(error_msg);
(int i = 0; i < 10; i++) {
    long i;
    /* ... */
  }
}

Compliant Solution

This compliant solution uses different, more descriptive variable namesa 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++
char system_msg[100];

void report_error(char const *error_msg) {
  char default_msg[80]  long j;
    /* ... */
  }
}

Exceptions

DCL01-C-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.

Code Block
bgColor#ccccff
langc
extern int ifname;
void f(char *name);  /* Declaration: no problem here */
/* ... */
void f(char *arg) {  /* Definition: no problem; arg doesn't hide name */
  /* Use arg */
}

DCL01-C-EX2: A temporary variable within a new scope inside of a macro can override an identifier in a containing scope. However,this exception does not apply to to the arguments of the macro itself.

Code Block
bgColor#ccccff
langc
#define SWAP(type, a, b) do { type tmp = a; a = b; b = tmp; } while(0)
 
void func(error_msg)
    strncpy(system_msg, error_msg, sizeof(system_msg));
  else
    strncpy(system_msg, default_msg, sizeof(system_msg));
  return;
}

int main(void) {
  int tmp char error_msg[80]= 100;
  /*int Ensurea error_msg isn't too long */= 10, b = 20;
  if (strlen(error_msg) >= sizeof(system_msg)) {
    error_msg[sizeof(error_msg) - 1] = '\0';
  }
  report_error(error_msg);
  /* ... */
}

When the block is small, the danger of reusing variable names is mitigated by the visibility of the immediate declaration. Even in this case, however, variable name reuse is not desirable.

...

SWAP(int, a, b); /* Hidden redeclaration of tmp is acceptable */
  SWAP(int, tmp, b); /* NONCOMPLIANT: Hidden redeclaration of tmp clashes with argument */
}

Risk Assessment

Reusing a variable name in a subscope can lead to unintentionally referencing an incorrect variable.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

DCL01-

A

C

low

Low

unlikely

Unlikely

medium

Medium

P2

L3

Automated Detection

The LDRA tool suite Version 7.6.0 can detect violations of this recommendation.

Splint Version 3.1.1 can detect violations of this recommendation.

...

Tool

Version

Checker

Description

Astrée
Include Page
Astrée_V
Astrée_V

Supported indirectly via MISRA C:2012 Rule 5.3.
Axivion Bauhaus Suite

Include Page
Axivion Bauhaus Suite_V
Axivion Bauhaus Suite_V

CertC-DCL01
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V
LANG.ID.ND.NESTNon-distinct identifiers: nested scope
Compass/ROSE




ECLAIR

Include Page
ECLAIR_V
ECLAIR_V

CC2.DCL01

Fully implemented

Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

C0795, C0796, C2547, C3334


Klocwork
Include Page
Klocwork_V
Klocwork_V

MISRA.VAR.HIDDEN


LDRA tool suite
Include Page
LDRA_V
LDRA_V

131 S

Fully implemented

Parasoft C/C++test
Include Page
Parasoft_V
Parasoft_V

CERT_C-DCL01-a
CERT_C-DCL01-b

Identifier declared in a local or function prototype scope shall not hide an identifier declared in a global or namespace scope
Identifiers declared in an inner local scope should not hide identifiers declared in an outer local scope

PC-lint Plus

Include Page
PC-lint Plus_V
PC-lint Plus_V

578

Fully supported

Polyspace Bug Finder

Include Page
Polyspace Bug Finder_V
Polyspace Bug Finder_V

CERT C: Rec. DCL01-C


Checks for variable shadowing (rule fully covered)

PVS-Studio

Include Page
PVS-Studio_V
PVS-Studio_V

V561, V688, V703, V711, V2015
RuleChecker

Include Page
RuleChecker_V
RuleChecker_V


Supported indirectly via MISRA C:2012 Rule 5.3.
Splint
Include Page
Splint_V
Splint_V



Related Vulnerabilities

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

References

Wiki Markup
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 5.2.4.1, "Translation limits"
\[[ISO/IEC PDTR 24772|AA. C References#ISO/IEC PDTR 24772]\] "BRS Leveraging human experience" and "YOW Identifier name reuse"
\[[MISRA 04|AA. C References#MISRA 04]\] Rule 5.2

Related Guidelines


...

Image Added Image Added Image AddedDCL00-A. Const-qualify immutable objects      02. Declarations and Initialization (DCL)       DCL02-A. Use visually distinct identifiers