I use the style:
char *x;
because this logically reflects how C parses declarations - the "definition follows use" rule. Don't think "x
is a char *
", think "*x
is a char
".
That lets you correctly parse definitions such as these:
const char *x;
(*x
is a const char
)
char * const x;
(x
, constant, after applying *
is a char)
char *x, y, **z;
(*x
is a char
, y
is a char
, **z
is a char)
Addendum:
Responding to a couple of the comments...
The idea that declarations can be written as TYPE LABEL;
ends up breaking down for more complex types, even if you ban multiple declarations on one line (which I don't agree with, either: int i, j;
has always been idiomatic C). For example, if I want to declare x
as "pointer to array of 10 char", then the type is char (*)[10]
(this is how you'd write it in a cast, for example). But you can't use the TYPE LABEL;
pattern:
char (*)[10] x; /* Not valid C :( */
Function pointers are another example. The usual rejoinder at this point is "Always use a typedef
for complex types like that!", and here I feel we must simply part ways and agree to disagree. Either you consider the logical inconsistencies and restrictions ("declare only one variable per line", "always build up complex types from simple typedefs") an appropriate price to pay for making declarations look the way you feel they should, or you don't.
In response to the Stroustrup comment I note that K&R uses the char *x
style, and here it seems we have the root of the C / C++ divergence on this matter of style.