Comments can make a program much easier to understand, but used heavily or poorly placed they can render good code unreadable. Use them conservatively. Good places to put comments include:
Major logical steps within the program or functions
Tricky steps within a program or function
Key variables, but do not document individual house-keeping variables, for example loop counters
Places where you do something out of the ordinary (this will help others to debug the code)
Places where you do something particularly clever (the technique might be useful for others)
Properties of code should only be commented if they are not obvious. By contrast, even seemingly obvious global properties and invariants may need to be made explicit. However, this doesn't have to be through comments. The assert()
macro is an excellent executable comment. There are a few guidelines when writing comments:
If your code needs a comment to be understood then you should look for ways to rewrite it so that it's clearer.
Comments should be comprehensible to other people, not just yourself.
Never write comments that might become incorrect or out of date. An inaccurate or misleading comment is worse than no comment at all.
The size of a comment should be proportional to the size of the code that it refers to.
All comments should be correctly formatted (see Appendix C, C Coding Standards).