Comments begin with the sequence /*
and end with */
.
For example we might find such a line in a C program:
num_stud = num_stud + 1 ; /* A student has been added */Such in-line comments can be useful when describing why a particular line of a program is there. We, probably more often, find block comments. These are often designated like this:
/* * add_stud() - add a student to a class * Arguments: * stud - ID number of the student being added * class - designator of the class to which the student is * being added * Return Value: * the new number of students in the class. If that is the * same as the old number of students, then the student was * not added. * Algorithm: * 1. See if the class is at or over it's limit * 2. If so, then return the current number of students * 3. Otherwise, check to see if the student is already * in the class. If so return the current number * of students. * 4. Otherwise, insert the student into the class list * in alphabetical order based on the last name (and * first name if the last names are the same.) * 5. Return 1 + the old number of students in the class. */This block of comments will preceed a function called
add_stud
and describes what the function does.
Notice that we've put a one-line description of what this function
does first.
Then we have sections that describe specific parts of the function.
Exactly what these parts are referring to will be discussed in
the next part.
We normally have one such block at the beginning of each function
in a program and one at the beginning of the whole program.
The one at the beginning of a program including add_stud
might look like:
/* * Student Scheduler * by Brian L. Stuart * Started: 6/15/94, Last Revision: 8/25/95 * * This program provides a basic student scheduling system. . . . */and would go on to describe the basic purpose and organization of the program. It's also helpful at this point in the comments to describe any limitations or assumptions that the program makes.
Finally, we wrap up with a few dos and don'ts about commenting.
Having said that, you might think it's not possible to over-comment a program. Comments that don't add any additional information will clutter up a program and make it harder to read. For example:
x = 5 ; /* Set x to 5 */
doesn't tell anyone who knows C anything they didn't already know
from looking at the statement itself.
Now it might be useful to tell the reader why x
is
being set to 5.
But that it is being set will be clear enough to anyone who knows
as much about C as you do.