declaring variable

Steve Summit scs at adam.pika.mit.edu
Sat Apr 8 14:50:40 AEST 1989


In article <26707 at tiger.oxy.edu> bagpiper at oxy.edu (Michael Paul Hunter) writes:
>A friend of mind had a program that wasn't working properly.
>Within this program was a declaration that was similar to:
>double A,
>       B,
>       fooY,
>       fooX,
>       whelp; /* <--- note this */
>       WhatAmI,
>       AndMoreVariables;

I see this style often, and I don't particularly like it.
Besides the potential for the error illustrated, this style
reflects a bit of compulsive ordering which accomplishes nothing.
I can think of three potentially valid ways of ordering
declarations: alphabetically, in order of use, or grouped in some
kind of functional categories.  Grouping variables by type
accomplishes nothing.

(Think about it.  Aside from the information they impart to the
compiler, declarations can be read by people to determine needed
information.  Usually, the needed information is a variable's
type, so ordering the declarations by type, i.e. the unknown, is
backwards, sort of like sorting a book's index by page number.)

Grouping declarations in this way also makes it hard to perform
isolated modifications.  Suppose, for example, that the variable
"A" is to be conditionally compiled out.  As it stands, I can't
just slap an #ifdef around it:

	#ifdef needvariableA
	double A,
	#endif
	       B,

Instead, I have to insert an extra "double" in front of B, making
it show up unnecessarily in a diff listing.  I also have to
change A's trailing comma to a semicolon, for the day when it
gets compiled in again.

(This is not a forced example; it came up several times when I
was getting kermit to fit on a non-split-I&D pdp11 by #ifdeffing
out huge chunks of it.  I'll admit that it's a fine point, but
style often revolves around fine points.)

Before you chide me for complaining about having to change a
comma to a semicolon in my #ifdef example, I'll point out that
this sort of thing probably led to the original bug: someone
added WhatAmI and AndMoreVariables without remembering to change
the semicolon after whelp to a comma.

I find it useful to place each declaration on its own line, with
its own type-specifier, unless the variables are very closely
related.  That is, I'd write

	int apples;
	int oranges;

only using commas in an example like

	int x, y;

where x and y are the cartesian coordinates of a single point.

When each declaration stands alone, you can add, delete,
rearrange, #ifdef, etc. to your heart's content, without annoying
syntax errors.

No complaints about the extra keystrokes involved in repeating
the type-specifiers, please.

                                            Steve Summit
                                            scs at adam.pika.mit.edu



More information about the Comp.lang.c mailing list