There are two kinds of comments in C++: single-line and paired. A single-line comment starts with a double slash (//
) and ends with a newline. Everything to the right of the slashes on the current line is ignored by the compiler. A comment of this kind can contain any text, including additional double slashes.
The other kind of comment uses two delimiters (/*
and */
) that are inherited from C. Such comments begin with a /*
and end with the next */
. These comments can include anything that is not a */
, including newlines. The compiler treats everything that falls between the /*
and */
as part of the comment.
A comment pair can be placed anywhere a tab, space, or newline is permitted. Comment pairs can span multiple lines of a program but are not required to do so. When a comment pair does span multiple lines, it is often a good idea to indicate visually that the inner lines are part of a multiline comment. Our style is to begin each line in the comment with an asterisk, thus indicating that the entire range is part of a multiline comment.
Programs typically contain a mixture of both comment forms. Comment pairs generally are used for multiline explanations, whereas double-slash comments tend to be used for half-line and single-line remarks:
#include <iostream>
/*
* Simple main function:
* Read two numbers and write their sum
*/
int main()
{
// prompt user to enter two numbers
std::cout << "Enter two numbers:" << std::endl;
int v1 = 0, v2 = 0; // variables to hold the input we read
std::cin >> v1 >> v2; // read input
std::cout << "The sum of " << v1 << " and " << v2
<< " is " << v1 + v2 << std::endl;
return 0;
}