Do not use the same variable name in two scopes where one scope is contained in another. For example,
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.
This noncompliant code example declares the errmsg
identifier at file scope and reuses the same identifier to declare a string that is private in the report_error()
subroutine. Consequently, the program prints "The error is Local error" rather than "The error is Global error."
$errmsg = "Global error"; sub report_error { my $errmsg = shift(@_); # ... print "The error is $errmsg\n"; }; report_error("Local error"); |
This compliant solution uses different, more descriptive variable names.
$global_error_msg = "Global error"; sub report_error { my $local_error_msg = shift(@_); # ... print "The error is $local_error_msg\n"; }; report_error("Local error"); |
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.
Hiding variables in enclosing scopes can lead to surprising results.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL01-PL | Low | Probable | Medium | P4 | L3 |
Tool | Version | Checker | Description |
---|---|---|---|
B::Lint | 5.0 | .* masks earlier declaration in same scope | Implemented |
SEI CERT C Coding Standard | DCL01-C. Do not reuse variable names in subscopesSEI CERT C++ Coding Standard |
---|---|
SEI CERT C++ Coding Standard | VOID DCL01-CPP. Do not reuse variable names in subscopes |
[Wall 2011] | perlsub |