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.