Coding Style for local variables

Stephen Hemminger stephen at networkplumber.org
Tue Jun 11 17:50:55 CEST 2024


On Tue, 11 Jun 2024 16:10:33 +0100
Ferruh Yigit <ferruh.yigit at amd.com> wrote:

> On 6/10/2024 4:10 PM, Morten Brørup wrote:
> > The coding style guide says:
> > 
> > "Variables should be declared at the start of a block of code rather than in the middle. The exception to this is when the variable is const in which case the declaration must be at the point of first use/assignment. Declaring variable inside a for loop is OK."
> > 
> > Since DPDK switched to C11, variables can be declared where they are used, which reduces the risk of using effectively uninitialized variables. "Effectively uninitialized" means initialized to 0 or NULL where declared, to silence any compiler warnings about the use of uninitialized variables.
> > 
> > Can we please agree to remove the recommendation/requirement to declare variables at the start of a block of code?
> >   
> 
> My concern is it may break the consistency in the code.
> If there is an existing function that defines N variables at the
> beginning of the function, new feature defines a new variable close the
> the feature block, this inconsistency bothers me more than all variables
> being defined at top.

There are few places where putting declarations in middle makes sense, like
   for (int i = 0; i < 10; i++)

> 
> Variables being defined on top only bothers me when function is too big
> and I can't see the variable declaration at the same time while I am
> reading the code.

Then the function is too big to start with!

> If functions is small enough to fit ~50% of my screen, locations doesn't
> really matter, I can still observe (effectively) uninitialized variables
> etc...
> Instead of trying to optimize big functions, I am for doing other way
> around to encourage smaller functions.

Agreed

> (Indeed I prefer 80 column limit with 8 space indentation for exact same
> reason, this *artificial* limit only allows some number of indentation
> and at some point forces developer to extract some part of code as new a
> function.)



More information about the dev mailing list