``When the code and the comments disagree, both are probably wrong.'' - Norm Schryer
The comments should describe what is happening, how it is being done, what parameters mean, which globals are used and which are modified, and any restrictions or bugs. Avoid, however, comments that are clear from the code, as such information rapidly gets out of date. Comments that disagree with the code are of negative value. Short comments should be what comments, such as ``compute mean value'', rather than how comments such as ``sum of values divided by n''. C is not assembler; putting a comment at the top of a 3-10 line section telling what it does overall is often more useful than a comment on each line describing micrologic.
Comments should justify offensive code. The justification should be that something bad will happen if unoffensive code is used. Just making code faster is not enough to rationalize a hack; the performance must be shown to be unacceptable without the hack. The comment should explain the unacceptable behavior and describe why the hack is a ``good'' fix.
Comments that describe data structures, algorithms, etc., should be
in block comment form with the opening
/*
in columns 1-2, a
*
in column 2 before each line of comment text,
and the closing
*/
in columns 2-3.
/*
* Here is a block comment.
* The comment text should be tabbed or spaced over uniformly.
* The opening slash-star and closing star-slash are alone on a line.
*/
Note that grep '^. *' will catch all block comments in the
file.
Some automated program-analysis
packages use different characters before comment lines as
a marker for lines with specific items of information.
In particular, a line with a
`-
'
in a comment preceding a function
is sometimes assumed to be a one-line summary of the function's
purpose.
Very long block comments such as drawn-out discussions and copyright
notices often start with
/*
in columns 1-2, no leading
*
before lines of text, and the closing
*/
in columns 1-2.
Block comments inside a function are appropriate, and
they should be tabbed over to the same tab setting as the code that
they describe.
One-line comments alone on a line should be indented to the tab
setting of the code that follows.
if (argc > 1) {
/* Get input file from command line. */
if (freopen(argv[1], "r", stdin) == NULL) {
perror (argv[1]);
}
}
Very short comments may appear on the same line as the code they describe, and should be tabbed over to separate them from the statements. If more than one short comment appears in a block of code they should all be tabbed to the same tab setting.
if (a == EXCEPTION) {
b = TRUE; /* special case */
} else {
b = isprime(a); /* works only for odd a */
}