Remove declaration-after-statement C warning

Bart Massey bart at cs.pdx.edu
Thu Sep 12 10:39:50 PDT 2013


On Thu, Sep 12, 2013 at 6:19 AM, Mouse <mouse at rodents-montreal.org> wrote:
>>> Whenever possible, variables should be declared at point of first
>>> assignment, so that it is clear that they have been initialized.
>
> There's nothing that says a top-of-block declaration can't include an
> initializer (to a dummy value if necessary).

A dummy initializer doesn't solve the problem. If you initialize the
variable to a non-useful value, it's only marginally better than not
initializing it at all: if you then use the variable before it's
gotten it's non-dummy value, that's still a bug.

>>> I know of no plausible SE case for declaring variables way up at the
>>> top of the block they are defined in other than tradition.
>
> It does make it easier to find the declaration of a variable when
> reading the code: check the top of each containing block, rather than
> all code up to the beginning of the containing function.  (Of course,
> you'd have to decide whether you consider that a "plausible SE case".)

If you search backward from the point of use, declaring nearer the
point of use will trivially result in less search than declaring
higher up. If you want to find the declaration of a variable
independent of the point of use, you are probably using grep or the
search function of your text editor anyhow.

>>> It was originally done that way to make it easier for Fortran
>>> compilers, AFAIK.
>
> A C feature was done to make it easier for FORTRAN compilers?  I'm not
> sure what that could even _mean_.

It means that language designers are conservative, and tend to adopt
conventions from earlier languages. Fortran, Algol-68, Pascal and C up
to C90 require declaration-before-code. At some later point, everyone
decided that this restriction didn't make compilers noticeably easier
and was kind of painful. Java, SML, Haskell, and C post-C99 allow
mixing declarations with code.

Our language, Nickle, treats definitions as first-class objects,
allowing things like

    scanf("%d %d", &(int x), &(int y));

that are really convenient.

--Bart


More information about the xorg-devel mailing list