Thinking in C++, 2nd ed. Volume 1
Parentheses, braces, and
indentation
You may notice the formatting style in this book is
different from many traditional C styles. Of course, everyone thinks their own
style is the most rational. However, the style used here has a simple logic
behind it, which will be presented here mixed in with ideas on why some of the
other styles developed.
The formatting style is motivated by one thing:
presentation, both in print and in live seminars. You may feel your needs are
different because you don’t make a lot of presentations. However, working code
is read much more than it is written, and so it should be easy for the reader to
perceive. My two most important criteria are “scannability” (how easy it is for
the reader to grasp the meaning of a single line) and the number of lines that
can fit on a page. This latter may sound funny, but when you are giving a live
presentation, it’s very distracting for the audience if the presenter must
shuffle back and forth between slides, and a few wasted lines can cause
this.
Everyone seems to agree that code inside braces should be
indented. What people don’t agree on – and the place where there’s the most
inconsistency within formatting styles – is this: Where does the opening brace
go? This one question, I think, is what causes such variations among coding
styles (For an enumeration of coding styles, see C++ Programming Guidelines, by
Tom Plum and Dan Saks, Plum Hall
1991.) I’ll try to convince you that many of today’s coding styles come from
pre-Standard C constraints (before function prototypes) and are thus
inappropriate now.
First, my answer to that key question: the opening brace
should always go on the same line as the “precursor” (by which I mean “whatever
the body is about: a class, function, object definition, if statement, etc.”).
This is a single, consistent rule I apply to all of the code I write, and it
makes formatting much simpler. It makes the “scannability” easier – when you
look at this line:
int func(int a);
you know, by the semicolon at the end of the line, that
this is a declaration and it goes no further, but when you see the
line:
int func(int a) {
you immediately know it’s a definition because the line
finishes with an opening brace, not a semicolon. By using this approach, there’s
no difference in where you place the opening parenthesis for a multi-line
definition:
int func(int a) { int b = a + 1; return b * 2; }
and for a single-line definition that is often used for
inlines:
int func(int a) { return (a + 1) * 2; }
Similarly, for a class:
class Thing;
is a class name declaration, and
class Thing {
No comments:
Post a Comment