A comment is a piece of descriptive text which explains some aspect of a program. Program comments are totally ignored by the compiler and are only intended for human readers. C++ provides two types of comment delimiters:
* Anything after // (until the end of the line on which it appears) is considered a comment.
* Anything enclosed by the pair /* and */ is considered a comment.
Listing 1.6 illustrates the use of both forms.
Listing 1.6
#include < iostream.h >
/* This program calculates the weekly gross pay for a worker,
based on the total number of hours worked and the hourly pay
rate. */
int main (void)
{
int workDays = 5; // Number of work days per week
float workHours = 7.5; // Number of work hours per day
float payRate = 33.50; // Hourly pay rate
float weeklyPay; // Gross weekly pay
weeklyPay = workDays * workHours * payRate;
cout << "Weekly Pay = " << weeklyPay << '\n';
}
Comments should be used to enhance (not to hinder) the readability of a program. The following two points, in particular, should be noted:
* A comment should be easier to read and understand than the code which it tries to explain. A confusing or unnecessarily-complex comment is worse than no comment at all.
* Over-use of comments can lead to even less readability. A program which contains so much comment that you can hardly see the code can by no means be considered readable.
* Use of descriptive names for variables and other entities in a program, and proper indentation of the code can reduce the need for using comments.
The best guideline for how to use comments is to simply apply common sense.