473,767 Members | 2,138 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Commenting style?

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!
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Jan 11 '07
100 4745
fn*****@fmi.uni-sofia.bg (Angel Tsankov) wrote (abridged):
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.

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

Jan 13 '07 #21
>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.
}
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)?
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Jan 13 '07 #22
Angel Tsankov wrote:
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();

--
Seungbeom Kim

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

Jan 13 '07 #23
Angel Tsankov wrote:
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++.m oderated. First time posters: Do this! ]

Jan 13 '07 #24
fn*****@fmi.uni-sofia.bg (Angel Tsankov) wrote (abridged):
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.

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

Jan 13 '07 #25
Andrew Marlow wrote:
On Thu, 11 Jan 2007 10:21:59 -0500, Angel Tsankov wrote:
>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 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.

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

Jan 14 '07 #26
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.
{
...
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Jan 14 '07 #27
kevin cline wrote:
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
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Jan 14 '07 #28

Dave Harris wrote:
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.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Jan 14 '07 #29
* 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++.m oderated. First time posters: Do this! ]

Jan 14 '07 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

46
2493
by: Profetas | last post by:
Hi, I know that this is off topic. but I didn't know where to post. Do you comment your source code while coding or after coding. for example: you write a procedure and after it is working, you'll comment it.
9
1876
by: | last post by:
Does C++/CLI have XML style commenting like C#?? If i do /// I dont get the completion like C#
8
1864
by: lallous | last post by:
Hello I've been programming for a number of years, however my commenting style is always different. Sometimes I use something like: /************************ * method .... * comments... *************************/
0
10169
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10013
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9960
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9841
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7383
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6655
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5280
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5424
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3930
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.