...
Wiki Markup |
---|
In this noncompliant code example, a programmer or code reviewer mightcould mistakenly believe that the variables {{src}} and {{c}} are both declared asto be type {{int}}. In fact, {{src}} is of type {{int\[\]}}, while {{c}} has a type of {{int}}. |
...
This example declares the array in an antiquated and unpopular style, with the brackets appearing after the variable name. Arrays should be declared as type[] name
, for improved clarity.
Compliant Solution
...
In this noncompliant code example, the programmer declared multiple variables, including an array, on the same line. All instances of the type T
have access to methods of the class Object
. However, it is easy to forget that arrays require special treatment when some of these methods are overridden.
...
When a method of Object
like toString()
is overridden, a programmer might accidentally provide an implementation for type T
that fails to account for the fact that c
is an array of T
, rather than a reference to an object of type T
.
Code Block |
---|
// The oversight leads to an incorrect implementation public String toString(){ return a.toString() + b.toString() + c.toString() + d.toString(); } |
However, the real intent might could have been to invoke toString()
on each individual element of the array c
.
...
This compliant solution places each declaration on its own line, as well as using the preferred notation for array declaration.
...
DCL04-01: Note that the declaration of a loop counter in a for statement is in violation of this recommendation , because the declaration is not on its own line with an explanatory comment about the role of the variable. However, declaration of loop indices in for statements is not only a very common idiom; it also provides the benefit of restricting the scope of the loop index to that of the for loop itself. These are sufficient reasons to relax this guideline in this specific case.
...
Declaration of more than one variable per line may could reduce code readability and lead to programmer confusion.
Guideline | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL01-J | low | unlikely | low | P3 | L3 |
Other Languages
Related Guidelines
This guideline appears in the C Secure Coding Standard as : DCL04-C. Do not declare more than one variable per declaration.This guideline appears in
the C++ Secure Coding Standard as : DCL04-CPP. Do not declare more than one variable per declaration.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this guideline on the CERT website.
...