Commenting style?

D

Dave Harris

Can someone recommend a good source of C/C++ coding style.
Specifically, I am interested in commenting style and in
particular how to indent comments and the commented code, rather
than when to use comments. Thanks in advance!

I've not read "C++ Coding Standards" by Sutter and Alexandrescu, but I'd
be astonished if it wasn't worth reading:
http://www.gotw.ca/publications/c++cs.htm

Beyond that... the answer will probably depend on the tools available.

For example, I strongly dislike code commented out with #if 0/#endif, or
with block comments, because I use searching tools roughly equivalent to
grep which find false hits in it (ie, matches in code that won't be
compiled). If you use // comments, you can tell each line is commented
even when it is printed in isolation.

And this is practical for me because I have an editor which can add or
remove line-comments to multi-line selections, so they are as easy for me
as any other kind of comment. If I had to laboriously put // at the start
of each line I'd be less keen.

I suspect some places use commenting standards that were laid down before
decent tools were available - perhaps before // itself was available.
Which is fair enough if you have an existing code base, but it's not
what's best if you are picking a coding standard from scratch today.

Beyond that... I don't like to see vertical space wasted, so I strongly
dislike comments like:

/*
* Just one line here.
*/

which take three lines where one is needed. I also strongly dislike
bureaucratic comments which state the obvious. It's a good idea to use a
tool like Doxygen and learn what it can generate for itself - function
signatures.

I probably average a little under one comment per function. Most functions
warrant a single line explaining what they are for in better English than
the function name itself. Some functions don't need even that because they
are obvious, and some functions need more comments in their code body
because they aren't obvious.

Obvious is good, but I find good comments are easier to read than good
code. With well-commented code I tend to read the comments until I get to
the bit I understand, then read the code. Comments should be at a higher
level of abstraction, and each should cover a block of code rather than be
a line-by-line commentary.

I find it natural to indent comments to the same level as the code they
are commenting:

/// This comment is for clients explaining what the function is for.
int function() {
// This comment explains the implementation, if necessary.
return 42; // Comments can go on the same line to save space.
}


-- Dave Harris, Nottingham, UK.
 
S

Seungbeom Kim

Angel said:
Can someone recommend a good source of C/C++ coding style. Specifically,
I am interested in commenting style and in particular how to indent
comments and the commented code, rather than when to use comments.

Keep away from fancy formatting, such as a box drawn with lots of stars.
Hard-to-edit comments are likely to be left out-of-date with the code
they explain. Be concise in the formatting.
(Possible exceptions include a few which are not meant to edited often.)

And I'd like to add that good comments describe *why* something is done,
rather than *what* is done by the code (which the code already says).

Useless:
// increment x and call f
++x;
f();

Useful:
// x should be incremented before calling f because ...
++x;
f();
 
A

Angel Tsankov

Can someone recommend a good source of C/C++ coding style.
I've not read "C++ Coding Standards" by Sutter and
Alexandrescu, but I'd
be astonished if it wasn't worth reading:
http://www.gotw.ca/publications/c++cs.htm

Beyond that... the answer will probably depend on the tools
available.

For example, I strongly dislike code commented out with #if
0/#endif, or
with block comments, because I use searching tools roughly
equivalent to
grep which find false hits in it (ie, matches in code that
won't be
compiled). If you use // comments, you can tell each line is
commented
even when it is printed in isolation.

And this is practical for me because I have an editor which can
add or
remove line-comments to multi-line selections, so they are as
easy for me
as any other kind of comment. If I had to laboriously put // at
the start
of each line I'd be less keen.

I suspect some places use commenting standards that were laid
down before
decent tools were available - perhaps before // itself was
available.
Which is fair enough if you have an existing code base, but
it's not
what's best if you are picking a coding standard from scratch
today.

Beyond that... I don't like to see vertical space wasted, so I
strongly
dislike comments like:

/*
* Just one line here.
*/

which take three lines where one is needed. I also strongly
dislike
bureaucratic comments which state the obvious. It's a good idea
to use a
tool like Doxygen and learn what it can generate for itself -
function
signatures.

I probably average a little under one comment per function.
Most functions
warrant a single line explaining what they are for in better
English than
the function name itself. Some functions don't need even that
because they
are obvious, and some functions need more comments in their
code body
because they aren't obvious.

Obvious is good, but I find good comments are easier to read
than good
code. With well-commented code I tend to read the comments
until I get to
the bit I understand, then read the code. Comments should be at
a higher
level of abstraction, and each should cover a block of code
rather than be
a line-by-line commentary.

I find it natural to indent comments to the same level as the
code they
are commenting:

/// This comment is for clients explaining what the function
is for.
int function() {
// This comment explains the implementation, if
necessary.
return 42; // Comments can go on the same line to save
space.
}

I totally agree, especially about comments being easier to read
than code, no matter how clear the code is!
I also agree about endline comments. Steve McConnell, for
instance, recommends using endline comments in the following
cases: to annotate data declarations; and to mark the end of a
block [Code Complete, 2nd Edition]. I have found both cases of
endline comments very convenient and I think that in addition to
that, endline comments may also be used in cases such as the one
shown above to save space. However, the following question arises
with endline comments: Should one try to indent adjacent endline
comments so that they start on the same column?

I also find it natural to indent comments the same level as the
code they are commenting. Having no empty line between a comment
and the commented code is especially convenient and practical if
the comment occupies a single line and applies to the line of
code that immediatly follows it. But what if the comment applies
to several lines of code? I find it very hard to make that clear
while keeping the code neat. For instance, I might decide that
the commented code needs some empty lines which, on second
glance, makes me think exactly which lines of code the comments
applies to.

Now, a question comes to me regarding punctuation: I have found
that when used at the end of a comment, colons :)) "link" the
comment with the code. Likewise, question marks (?) make you
think of what is happening. Sometimes, even an exclamation mark
(!) may be used to draw attention to something that should or
should not be done. But what about the cases where neither of the
above marks is appropriate? Should one use a ful lstop (.) to
mark the end of sentences? And does this apply to all types of
comments (full-line, endline, C-style, C++-style)?
 
P

Phlip

Angel said:
Can someone recommend a good source of C/C++ coding style. Specifically,
I am interested in commenting style and in particular how to indent
comments and the commented code, rather than when to use comments.

Treat a comment as a failed opportunity to make the code clearer and more
self-documenting.

Given unclear and unself-documented code, you could improve it by
refactoring, upgrading variable names, shortening functions, and adding
unit
tests. That's a better way to spend your time when it reduces the odds of
having bugs, and increases your subsequent project velocity.

(You do _have_ unit tests, don't you?)

If you fail to make the code clearer, express that failure as a suggestion,
with TODO for things that _will_ improve the code, and CONSIDER for things
that _might_.

For example, instead of saying "this recurses now", say...

// CONSIDER replace tail-recursion with looping here?

....or instead of "this Frob here interacts remotely with the Frobomat over
there", say:

// TODO move this Frob into the Frobomat, instead of here where
// it couples with the Mobomat

Then add to your Makefile or equivalent a 'todo' target that grep's for the
TODO and CONSIDER markers. At the end of each iteration (you do _have_
iterations, don't you?) with a session of grepping for TODOs and fixing
them, then CONSIDERs and reviewing them.

--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
 
D

Dave Harris

I also agree about endline comments. Steve McConnell, for
instance, recommends using endline comments in the following
cases: to annotate data declarations; and to mark the end of a
block [Code Complete, 2nd Edition].

In my view ends of blocks don't generally need comments to mark them.

However, the following question arises with endline comments: Should
one try to indent adjacent endline comments so that they start on
the same column?

If I have more to say than will fit at the end of the line, I make it a
normal comment on the line above. I don't have set places for using
endline comments. I use them whenever the comment is short and I want to
save space.

I think trying to line up comments with tabs or spaces is a mugs game.
Including things like:

int x; // Some value.
std::vector<int> table; // Some other value.

It's just too much trouble to maintain. If the vector changes to something
longer, the comment indent will have to change and I'll have to go back
and reformat the other comments too. And although it looks prettier I
don't believe it is any easier to read.

For instance, I might decide that the commented code needs some
empty lines which, on second glance, makes me think exactly which
lines of code the comments applies to.

It can't be helped. Credit readers with some intelligence; they'll figure
it out. The comments give them some hints but if they really need to know
what's going on they'll read the code itself. Code is definitive. Comments
aren't.

If you must, you can put another comment at the end of the code or at the
start of the next code. Or put braces around it all and let the reader
figure out that the comment applies to all the code inside the braces. The
situation is rare enough that common sense solutions surely suffice.

Should one use a ful lstop (.) to mark the end of sentences?

I think so, yes. I tend to write comments in English, with normal English
punctuation. That's kinda the point: they are not supposed to be code.

And does this apply to all types of comments (full-line, endline,
C-style, C++-style)?

Yes. (I rarely use C-style comments, if by that you mean /* */.)

-- Dave Harris, Nottingham, UK.
 
D

Damien Kick

Andrew said:
I think this is going to turn into a very long thread. I forsee everyone
and his dog chipping in with their $0.02. I can't resist either!


Stroustrup writes about a few of the things that he'd like to see in the
future for C++ in _Design and Evolution_. IIRC, one of the things about
which he writes as slowing down the progress of C++ is the continued use
of plain old ASCII files as the media for source code. I think these
perennially useless debates about indentation, whether or not to put
blank lines or comment lines between function definitions, etc., are a
symptom of this issue. Nobody ever agrees on these things, nobody ever
will, and nobody ever should have to do so. Again, IIRC, Stroustrup
imagines a system in which source is stored as some kind of database of
tokens, as opposed to an ASCII file. With such a system, displaying the
code as glyphs on the screen would be merely an issue of presentation.
If Sally likes to look at code blocks indented two spaces, it can be
presented to her as such. If Joe likes four spaces, then that is what
he gets. Even with our current state of code as ASCII, we still can
achieve this kind of variable presentation style per user preference
with tools like astyle or indent. There would need to be a canonical
style to be used when checking code into SCM, which could be achieved by
running astyle, for example, with some kind of hook or trigger when
checking in a source file. But each user could have her own personal
set of astyle rules to reformat the code as she wished after having
checked it out to make an update.
 
K

Keith H Duggar

kevin said:
All the comments that follow are completely useless. They
consume screen space while adding no information, merely
stating what is obvious to a C++ programmer with more than
a month's experience. Code is much easier to read and
understand when it is uncluttered.

For what's it worth, I fully agree with Kevin and Seungbeom
Kim. Comments like

//includes

//default constructor

//private data

//member functions

etc are totally useless and detrimental to code clarity.
Steve Mcconnell's advice in "Code Complete" on commenting
and more importantly /naming/ is excellent. Code written
with carefully chosen, obvious, and descriptive names is
nearly self-documenting. You can augment this with summary
comments explaining the general structure, algorithms, etc
and comments that note particularly tricky or subtle
points.

Keith
 
P

perrog

Angel Tsankov skrev:
Can someone recommend a good source of C/C++ coding style.
Specifically, I am interested in commenting style and in
particular how to indent comments and the commented code, rather
than when to use comments. Thanks in advance!

If you don't use /** */ and /// would likely not have any autodoc
generator. Anyway, let the comment follow the declaration (or
definition) on the next line, with one extra forward indent.
Descriptions for scopes (declaration regions) are placed after the name
identifier, but before the "{"-bracket, but don't forward indent.
Longer texts are optionally placed in multi-line comments and because
they are longer, such arent suitable for declarations, definitions and
scopes. If single line comment must line break, use a inline indent in
the comment to designate a paragraph. If this was a documentation
style, then comments for reference would tab forward, and internal
comments for programmers would tab backward. Example:

//------------------------ ... ------------------------
// Header.h
//------------------------ ... ------------------------

/*
Description comment are better written in multi-line
comments, but you don't need to write a thesis.
*/

//------------------------ ... ------------------------
// Group comment

struct A
// Scope comment.
{
int field;
// Comment for references, one step indended. Line continuation
// may break lines in if inline indented in the comment things
// gets easier to read, but this is opposit how
// printed media works.
// Next paragraph shouldn't be initially inline tabbed.

int field;
// IDEs that automatically softwraps very long lines may
automatically indent the line continuation, like this.
Then just write a long line.
};

enum
// scope comment
{
var1,
// Declaration comment for enumerator definition
var2
};

#define MACRO() ()
// Declaration comment for macro definitions

//========================= ... =========================
// class Object
//========================= ... =========================

class Object
// Scope comment again,
{
//------------------------ ... ------------------------
// Function group comment
//------------------------ ... ------------------------

Object() { }
// Declaration comment for single-line inline.
Object(const Object &cpy);
// Declaration comment
~Object()
// Scope comment for inline. Or should one use
// declaration/definition comment?
{
}

// This is a backward tabbed comment for programmers.
// And one (or should it be two or three?) empty line breaks the
// function group. Thus foo isn't part of above function group.
void foo();
// declaration comment
};

//------------------------ ... ------------------------
// Object::Object(const Object &cpy)
//------------------------ ... ------------------------

Object::Object(const Object &cpy)
// scope comment yet again for inlined functions.
{
...
}
 
A

Alf P. Steinbach

* Noah Roberts:
My personal preference is to follow the smells theory in which code
commenting is a smell:

Depends on the kind of comment.

A comment explaining a cryptic piece of code generally stinks, right,
for seldom is there any need for code to be cryptic. But even such
comments can be good and needed. For example, without template typedefs
and similar abstraction tools, currently lacking in C++, some template
constructions simply must be rather intricate, and then it's the lack of
an explanatory comment that reeks of week-old sushi and worse (ah, that
reminds me of secondary school, where a teacher had inquired about the
possibility of buying fish tongues from a pupil; the pupil placed the
sack of fish tongues behind something in the teachers' rest room...).

Comments that are in support of tools such as version control systems,
documentation generators and preprocessors are generally odor-free.

Also, structural comments that address the need for higher level
structural abstraction than C++ provides, i.e. that serve to place the
code in a higher level conceptual framework (like, what this and that
part of the code would correspond to in a language with module support),
are also generally odor-free.

But that doesn't mean that such comments should necessarily be used. In
one project -- it was a Java project, but that doesn't matter -- one
colleague had a problem with computing and comparing date-times. So I
made her a simple time difference class, which took maybe half an hour
to create. This she managed to use, after some guidance. But then it
didn't follow the project coding guidelines, which required JavaDoc
comments. As the author of that piece of code it was up to me to add
those comments, and I did, in minimal form. But while she (at least
seemingly) understood the original, with the added documentation
comments it was all suddenly very complex & ungrokkable, presumably
because the code size had nearly doubled and it was now all too easy to
read only the comments (which, per requirements, focused on the wrong
things for understanding) rather than the simple code itself.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
 
K

kevin cline

Dave said:
Obvious is good, but I find good comments are easier to read than good
code. With well-commented code I tend to read the comments until I get to
the bit I understand, then read the code. Comments should be at a higher
level of abstraction, and each should cover a block of code rather than be
a line-by-line commentary.

I prefer to move such blocks into separate functions, and then use the
comment for the function name.
 
J

James Kanze

Dave said:
I also agree about endline comments. Steve McConnell, for
instance, recommends using endline comments in the following
cases: to annotate data declarations; and to mark the end of a
block [Code Complete, 2nd Edition].
In my view ends of blocks don't generally need comments to mark them.

Unless your functions are too complex. (But of course, the
solution is to simplify the function, not to comment the end of
the blocks.)
If I have more to say than will fit at the end of the line, I make it a
normal comment on the line above. I don't have set places for using
endline comments. I use them whenever the comment is short and I want to
save space.
I think trying to line up comments with tabs or spaces is a mugs game.

I think you really can't avoid it, if the editor is set up
right. As soon as you enter //, the editor moves it over to the
predefined column.
Including things like:
int x; // Some value.
std::vector<int> table; // Some other value.
It's just too much trouble to maintain. If the vector changes to something
longer, the comment indent will have to change and I'll have to go back
and reformat the other comments too.

I'd expect any editor worthy of the name to do this
automatically. At the very most, you must enter a short command
to ask it to reformat the comments for an entire block.
And although it looks prettier I
don't believe it is any easier to read.

I think it depends. If you don't have syntax highlighting, it
definitly helps finding the comment, or even recognizing that
the comment is there. (But about the only time I can imagine
not having syntax highlighting is when printing to a black and
white printer.)

In practice, end of line comments are very, very rare in my code
anyway. I comment the class (using Doxygen), and the functions
there, and have almost no comments in the actual code. About
the only place I end up with end of line comments is for things
like enum values, and even then, most of the time, a couple of
them need more.
 
J

James Kanze

Seungbeom said:
And I'd like to add that good comments describe *why* something is done,
rather than *what* is done by the code (which the code already says).

Within a function, about the only comments I use are ones to
explain why some simple solution wasn't used. Commenting what
you didn't do, and why (i.e. the alternatives that you
considered and rejected), is often more useful than commenting
what you actually ended up doing. Presumably, the reader can
read C++, and can recognize the usual patterns and familiar
algorithms, and knows when and why they are used. Why some
apparently simpler solution wasn't appropriate is often more
useful information.
 
N

Noah Roberts

..moderated removed to allow free discussion.
* Noah Roberts:

Depends on the kind of comment.

Well, code smells are all about "depends".

"Note that a CodeSmell is a hint that something might be wrong, not a
certainty. A perfectly good idiom may be considered a CodeSmell because
it's often misused, or because there's a simpler alternative that works
in most cases. Calling something a CodeSmell is not an attack; it's
simply a sign that a closer look is warranted. "

http://c2.com/xp/CodeSmell.html

So everything you say may be true but doesn't contradict the "comments
are smells" theory.
 
D

Dave Harris

I prefer to move such blocks into separate functions, and then use the
comment for the function name.

Sometimes splitting code over separate functions help, and sometimes it
doesn't. Sometimes in order to understand the code I need to see it all in
one place; get it all in my head at once. For example, a variable may be
set up in one block and used in another, and these may be coupled such
that the blocks are hard to understand in isolation. You need to see how
it is used before you understand why it is set up in that particular way,
or vice-versa.

The idea that the function names should be the comments sounds fine, but I
don't find it works in practice. I like my comments to be written in plain
English, which is too wordy for function names. Verbose function names are
less readable than (reasonably) terse ones.

Here's an example to clarify:

/// Return true if this list has no members.
bool MyList::empty() const {
return head_ != NULL;
}

The comment is eight words rather than one. It explains what "empty"
means; once you know the explanation the word itself is enough, but I find
it does help to explain it somewhere once for people who don't know. When
I am reading other people's code there often seems to be a lot of
information in the author's mind that didn't make it into the code,
including a special vocabulary. Comments can help correct that.

Even if the function name is sufficient (which admittedly is probably the
case with such a standard name as "empty"), there is often more to say:

/// This is guaranteed O(1) where size() may be O(N).
bool MyList::empty() const {
return head_ != NULL;
}

That comment is for users of the function. Similar comments can explain
the implementation:

// Find the largest item. Although this looks like an O(N*N)
// algorithm, it is actually O(N) because the widget is memoised.

-- Dave Harris, Nottingham, UK.
 
A

Angel Tsankov

I also agree about endline comments. Steve McConnell, for
instance, recommends using endline comments in the following
cases: to annotate data declarations; and to mark the end of
a
block [Code Complete, 2nd Edition].
In my view ends of blocks don't generally need comments to
mark them.

Unless your functions are too complex. (But of course, the
solution is to simplify the function, not to comment the end of
the blocks.)
If I have more to say than will fit at the end of the line, I
make it a
normal comment on the line above. I don't have set places for
using
endline comments. I use them whenever the comment is short and
I want to
save space.
I think trying to line up comments with tabs or spaces is a
mugs game.

I think you really can't avoid it, if the editor is set up
right. As soon as you enter //, the editor moves it over to
the
predefined column.

Can you point out such an editor?
I'd expect any editor worthy of the name to do this
automatically. At the very most, you must enter a short
command
to ask it to reformat the comments for an entire block.

Again: example of an editor providing this functionality?
 
I

Ian Collins

Dave said:
The idea that the function names should be the comments sounds fine, but I
don't find it works in practice. I like my comments to be written in plain
English, which is too wordy for function names. Verbose function names are
less readable than (reasonably) terse ones.

Here's an example to clarify:

/// Return true if this list has no members.
bool MyList::empty() const {
return head_ != NULL;
}

The comment is eight words rather than one.

What's wrong with isEmpty()? Sums up the comment and is unambiguous.
 
R

Roy Smith

/// Return true if this list has no members.
bool MyList::empty() const {
return head_ != NULL;
}

The comment is eight words rather than one. It explains what "empty"
means; once you know the explanation the word itself is enough, but I find
it does help to explain it somewhere once for people who don't know. When
I am reading other people's code there often seems to be a lot of
information in the author's mind that didn't make it into the code,
including a special vocabulary. Comments can help correct that.

Even if the function name is sufficient (which admittedly is probably the
case with such a standard name as "empty"), there is often more to say:

/// This is guaranteed O(1) where size() may be O(N).
bool MyList::empty() const {
return head_ != NULL;
}

Not to mention the possibility that it might have been:

/// Empty the list
void MyList::empty() {
head_ = NULL;
}

Granted, seeing it used in context, or seeing that the return type is bool
would be pretty good clues that "empty" is being used as a predicate, not a
verb. But, my point is that what's obvious to the author is often not
obvious to a reader many years later.
 
K

Keith H Duggar

Seungbeom said:
That style of commenting falls into the same category as
this:

++x; // increment x

and I would object to it, unless the code is for
exposition of the relevant part of the language in a C++
textbook.

/** First Paragraph */
This is a good observation. Perhaps such comments should
also be avoided in textbooks as well? Those who learn from
such books may come to believe this is good style (after all
it's in a book!) and hence fall into the habit of writing
such useless comments. // End First Paragraph

/** Second Paragraph */
Books are not ASCII source code and are not bound by it's
limitations. Authors are free to use a variety of expository
tools (tables, line numbers, weights, styles, colors, etc)
and I have seen all these alternatives used in programming
textbooks. So don't we set a bad example by choosing the
useless redundant comment tool? // End Second Paragraph

/** Author */
Keith
 
J

James Kanze

Angel Tsankov wrote:

[...]
Can you point out such an editor?

Emacs has it more or less built into the C++ mode; you can't
avoid it. I use vim, and it's auto-indentation does pretty much
the same thing (although it's no where near as sophisticated
about it as vim).
Again: example of an editor providing this functionality?

Vi requires the extra command. Emacs does it more or less
automatically.

Every editor I've ever used (well, since ed), has had the
possibility of filtering lines of text through an external
program. This is what I used with vi. Editors like emacs have
a built in programming language, so you don't even need an
external filter.
 
K

kevin cline

Keith said:
/** First Paragraph */
This is a good observation. Perhaps such comments should
also be avoided in textbooks as well? Those who learn from
such books may come to believe this is good style (after all
it's in a book!) and hence fall into the habit of writing
such useless comments. // End First Paragraph

The fundamental problem is that actually programming generally pays
better
than teaching programming, so most people end up learning to program
from
mediocre programmers. Fortunately, some good programmers have written
books. Unfortunately, few schools seem to select those books.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,169
Latest member
ArturoOlne
Top