Should we remove -Wdeclaration-after-statement? - Mailing list pgsql-hackers

From Jelte Fennema-Nio
Subject Should we remove -Wdeclaration-after-statement?
Date
Msg-id CAGECzQQmeX+2ZAmGiUD_zJ4sRAJD5OBY_h+38WWv28fQhk_HPg@mail.gmail.com
Whole thread Raw
Responses Re: Should we remove -Wdeclaration-after-statement?
Re: Should we remove -Wdeclaration-after-statement?
List pgsql-hackers
Postgres currently requires all variables to be declared at the top of
the function, because it specifies -Wdeclaration-after-statement. One
of the reasons that we had this warning was because C89 required this
style of declaration. Requiring it everywhere made backporting easier,
since some of our older supported PG versions needed to compile on
C89. Now that we have dropped support for PG11 that reason goes away,
since now all supported Postgres versions require C99. So, I think
it's worth reconsidering if we want this warning to be enabled or not.

Personally I would very much prefer the warning to be disabled for the
following reasons:
1. It allows Asserts, ereports and other checks at the top of a
function, making it clear to the reader if there are any requirements
on the arguments that the caller should uphold.
2. By declaring variables at their first usage you limit the scope of
the variable. This reduces the amount of code that a reader of the
code has to look at to see if the variable was changed between its
declaration and the usage location that they are interested in.
3. By declaring variables at their first usage, often you can
immediately see the type of the variable that you are looking at.
Since most variables are not used in the whole function, their first
usage is pretty much their only usage.
4. By declaring variables at their first usage, you can often
initialize them with a useful value right away. That way you don't
have to worry about using it uninitialized. It also reduces the lines
of code, since initialization and declaration can be done in the same
line.
5. By declaring variables at their first usage, it is made clear to
the reader why the variable needs to exist. Oftentimes when I read a
postgres function from top to bottom, it's unclear to me what purpose
some of the declared variables at the top have.
6. I run into this warning over and over again when writing code in
postgres. This is because all of the other programming languages I
write code in don't have this restriction. Even many C projects I work
in don't have this restriction on where variables can be declared.



pgsql-hackers by date:

Previous
From: Ranier Vilela
Date:
Subject: Re: Fix Brin Private Spool Initialization (src/backend/access/brin/brin.c)
Next
From: Andreas Seltenreich
Date:
Subject: Failed assertion in joininfo.c, remove_join_clause_from_rels