Log in | Back to darenet.org

Development Team/Coding Standards/new

Comments

Comments can add immensely to the readability of a program, but used heavily or poorly placed they can render good code completely incomprehensible. It is far better to err on the side of too few comments rather than too many - at least then people can find the code. Also, if your code needs a comment to be understood, then you should look for ways to rewrite the code to be clearer. And comments that aren't there won't get out of date. An inaccurate or misleading comment hurts more than a good comment helps, so be sure to update or remove your comments as needed.

That being said, good places to put comments are:

  • a broad overview at the beginning of a module
  • data structure definitions
  • global variable definition
  • at the beginning of a function
  • tricky steps within a function

If you do something weird, a comment to explain why can save future generations from wondering what drug you were on and where to get it. If you do something clever, brag about it. Not only will this inflate your ego, but it will also subtly tip off others as to where to look first for bugs. Finally, avoid fancy layout or decoration.

NOTE: DO NOT use C++ style sing-line comments. It's consider bad practice to use them in a C program, and is not ANSI compliant.

You should also strive to doxify your comments, where suitable. Rambles, rants, and personal complaints do not provide any benefit to understanding code, please do not add them.

Examples:

/* single line comments look like this */
 
/*
 * Important single line comments look like multi-line comments.
 */
 
/*
 * Multiline comments look like this. Put the opening and closing
 * comment sequences on lines by themselves. Use complete sentences
 * with proper English grammar, capitalization, and punctuation.
 */
 
/* but you don't need to punctuate or capitalize one-liners */

The opening / of all comments should be indented to the same level as the code to which it applies, for example:

if (fubar()) {
	/*
	 * Fouled up beyond all recognition.  Print a nastygram
	 * and attempt to clean up.  If that doesn't work,
	 * die horribly, and try to crash the system while
	 * we're at it.
	 */
	...
}

If you put a comment on the same line as code, set it off from the code with a few tabs. Don't continue such a comment across multiple lines. For example:

printf("hi\n");		/* hello revisited */

In fact, try to avoid such comments altogether - if it`s not important enough to warrant a complete sentence, does it really need to be said?