Every declaration should be for a single variable, on its own line, with an explanatory comment about the role of the variable. Declaring multiple variables in a single declaration can cause confusion regarding the types of the variables and their initial values. If more than one variable is declared in a declaration, care must be taken that the type and initialized value of the variable is known.
Noncompliant Code Example
In this noncompliant code example, a programmer or code reviewer might mistakenly believe that the two variables src
and c
are declared as int
. In fact, src
has a type of int []
, while c
has a type of int
.
int src[], c;
Compliant Solution
In this compliant solution, each variable is declared on a separate line.
int src[]; /* source array */ int c; /* max value */
Although this change has no effect on compilation, the programmer's intent is clearer.
Noncompliant Example
In this noncompliant example, a programmer or code reviewer might mistakenly believe that both i
and j
have been initialized to 1. In fact, only j
has been initialized, while i
remains uninitialized.
int i, j = 1;
Compliant Solution
In this compliant solution, it is readily apparent that both i
and j
have been initialized to 1.
int i = 1; int j = 1;
Exceptions
DCL04-01: Trivial declarations for loop counters, for example, can reasonably be included within a for
statement:
for (int i = 0; i < mx; ++i ) { /* ... */ }
Other Languages
This rule appears in the C Secure Coding Standard as DCL04-C. Do not declare more than one variable per declaration.
This rule appears in the C++ Secure Coding Standard as DCL04-CPP. Do not declare more than one variable per declaration.