Writing good comments takes practice. However, it is a critical skill to acquire. It will make your code much easier to read, both for you and for other people. It will also help you get as many points as possible, especially for code that does not fully work.
Significantly fewer comments are required if you use good coding style:
Function names can be very long and English-like, e.g. read_input_file, compute_standard_deviation. Variable names are typically shorter e.g. infile, sum, count, num_vars, max_length.
Only use very short, generic variable names (e.g. x, y, i, j, ptr) in contexts where their purpose is obvious. For example, i and j are often used as indices for loops; x and y are often used as coordinates in geometrical or graphical algorithms.
Don't use a variable for one purpose (e.g. a loop index) and then reuse it later for another purpose (e.g. to store a count).
Global variables traditionally have names that are all capital letters, to distinguish them from normal variables.
At the start of the file, there should be a long block of comments containing:
There should be longish comments (e.g. 1-5 lines):
These commends should explain what the next piece of code does. Comments before a function should explain what inputs it expects and what outputs it returns.
Focus on how this code fits into the overall algorithm (e.g. "reads the database from the input file"). Comment things that might not be obvious to the reader.
Don't comment obvious things such as how many parameters a function takes, or numerical parameters whose names clearly indicate their purpose (e.g. xsize and ysize in a 2D array allocator), or the main goal of a function with a self-explanatory name like compute_standard_deviation.
There should be short comments (e.g. partial line)
If you can't explain an obscure piece of code with comments at the ends of lines, put a longer multi-line comment at the nearest convenient place above the obscure code.
Your documentation should describe
The main subject of the documentation should be the code. If it starts sounding like a short story about you, rephrase to make it focus more on the code.
If you could not get your approach to work, it is appropriate (and will probably get you more points) to describe how your approach was supposed to work.
If something doesn't work, say so. If a piece of code seems like a kludge (ugly hack), say so. The reader will eventually notice the problem anyhow: stating it explicitly saves them work and makes it clear that you saw the problem.
This page is maintained by Geoff Kuenning.