1.9. Comments

Time: 00:03:03 | Download: Large, Large (CC), Small | Streaming, Streaming (CC) | Slides (PDF)

Comments are information intended for people reading the source code and are ignored by the compiler during the compilation process. Programmers typically use comments to explain statements or computations that are not otherwise obvious, describe algorithms, provide references, etc. In short, they provide any information that might help readers understand the code and developers more easily maintain it.

// Comment that continues to the end of the line
(a)
/* A comment that continues until closed. This kind of comment can span multiple lines.*/
(b)
int x = y / z /* this assumes that z is not zero */ + w;
(c)
Two kinds of comments. C++ provides two sets of comment characters that allow programmers to create two slightly different kinds of comments:
  1. Source code may appear on the left side of the comment characters ( // ), but all characters appearing on the right form a comment (i.e., ignored by the compiler). This comment style may appear at the beginning of a line or provide brief information at the end of a statement.
  2. These are often called C-style comments as they are the only kind of comments that the C programming language supports. C-style comments conveniently form extended descriptions at the beginning of a program or function.
  3. Programmers can embed C-style comments inside statements because the compiler ignores them. Although the example is syntactically correct, it demonstrates a rarely used practice that can make reading the code unnecessarily difficult. However, it can be useful as a temporary debugging tool (see below).
One rule for comments

Programmers agree on one strict rule about comments: comments must make it easier for a human reader to understand a program and the purpose of any obscure operations..

Using Comments

Too few comments can leave a reader unsure about what a program is doing or how it connects to the original problem. However, too many or inappropriately placed comments can obscure the code and make it more difficult to read. Sadly, no formula tells programmers how to find the Goldilocks balance between too many and too few comments.

In the absence of standards (imposed by employers or instructors), programmers will develop and use a personal commenting style that works for them. I use the /* . . . */ style above a program, function, or a complex block of code to provide an overall description of the following code. I reserve the // style for placing comments inside the code. This practice generally produces code that is clean and easy to read. It also allows nesting comments when using them as a debugging tool (described next). The following program (described in greater detail in Chapter 2) demonstrates my commenting style.

/*
 * mortgage -- calculates the amount of a monthly mortgage payment based on the
 * principal (i.e., the amount borrowed), the annual percentage rate (APR), and
 * the number of years to pay off the loan.
 *
 * The program assumes one payment per month (i.e., 1 period = 1 month).
 * Therefore, the number of periods = the number of years * 12 and
 * the periodic interest rate = APR / 12.
 */


#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;


int main()
{
	double	p;					// principal-- loan amount 
	int	years;					// number of years of loan
	double	apr;					// annual percentage rate


	cerr << "Please enter the principal: ";
	cin >> p;

	cerr << "Please enter the APR: ";
	cin >> apr;

	cerr << "Please enter the number of years: ";
	cin >> years;


	cout.setf(ios::fixed);				// fixed point output
	cout.precision(2);				// two places after the .

	int	n = years * 12;				// years to periods
	double	r = apr / 12;				// APR to periodic rate

	double	payment = p * r / (1 - pow(1 + r, -n));	// periodic payment
	cout << "Monthly Payment: " << payment << endl;

	return 0;
}
Comments in a simple program. I like to use C-style comments for longer, running comments at the beginning of a program or function, and use single-line comments to provide brief statement-oriented comments.

The column of asterisks on the left edge of the top comment is not required. This commenting style was used extensively by C programmers and used extensively in the Unix source code. It remains popular with many programmers, and some text editors (e.g., gvim) add it automatically.

Here are my four "rules of thumb" for using comments:

  1. Use inline comments judiciously
  2. Add block comments above programs, functions, or a sequence of complex statements
  3. Be careful with nested comments
  4. Keep lines a reasonable length - don't just keep scrolling

Comments As A Debugging And Development Tool

While developing or debugging a program, there are times when it is helpful to temporarily remove code from the program, a technique called commenting out the code. We can imagine that a program contains some necessary code. Further, imagine that the programmer wants to try other versions - perhaps to simplify the code or make it more efficient. The programmer reverts to the original code if the new versions fail. Reversion is troublesome if the programmer removed the original code but simple if it's commented out.

The code may be necessary, but what if it contains a bug, especially one that crashes the program? Temporarily removing some code may help identify or locate a bug. Assuming we don't introduce new bugs when we comment out code, we know the bug is in the commented-out code if the program doesn't crash when it runs. Similarly, I also use comments in the demonstration programs and posted solutions to illustrate alternative approaches.

It is relatively easy to comment out code if the only "real" comment characters used are the //-style. Consider the following examples:

Original Code Commented Out Code
statement1;
statement2;	/* does something neat */
statement3;
statement4;
/*statement1;
statement2;	/* does something neat */
statement3;
statement4;*/
(a)
statement1;
statement2;	// does something neat
statement3;
statement4;
 
 
//statement1;
//statement1v1;
statement1v2;
statement2;	// does something neat
statement3;
statement4;
(b)
statement1;
statement2;	// does something neat
statement3;
statement4;
/*statement1;
statement2;	// does something neat
statement3;
statement4;*/
(c)
statement1;
statement2;	// does something neat
statement3;
statement4;
statement1;
//statement2;	// does something neat
statement3;
statement4;
(d)
Using /*...*/ comments as a debugging and development tool.
  1. The original comment is syntactically correct, but the second version interleaves the comments. The opening comment characters of the original comment are inside the added comment and skipped. The highlighted comment characters match, leaving the final comment characters unmatched, resulting in a syntax error.
  2. statement1; is the original code. A programmer is trying different versions with statement1v1; and statement1v2;. The programmer selects the final version by adding and removing comments as needed.
  3. The two comments nest without producing any new syntax errors in this example.
  4. It's also possible to comment out a single line of code; the two sets of comment markers do not conflict.

Visual Studio Comment "Tricks"

The Visual Studio editor has a couple of formatting commands that assist in commenting out code (which attests to the commonness of the technique).

Comment Out Code
  1. Highlight a block of code that you wish to comment out by pressing and holding the left mouse button while dragging the mouse pointer across the desired text
  2. Enter the key sequence Ctrl-K followed by Ctrl-C
Restoring Commented Out Code
  1. Highlight the commented-out code, including the comments
  2. Enter the key sequence Ctrl-K followed by Ctrl-U