Before our programs getmuch more complicated, we should see how C++(www.cppentry.com) handles comments. Comments help the human readers of our programs. They are typically used to summarize an algorithm, identify the purpose of a variable, or clarify an otherwise obscure segment of code. The compiler ignores comments, so they have no effect on the program’s behavior or performance.
Although the compiler ignores comments, readers of our code do not. Programmers tend to believe comments even when other parts of the system documentation are out of date. An incorrect comment is worse than no comment at all because it may mislead the reader. When you change your code, be sure to update the comments, too!
Kinds of Comments in C++(www.cppentry.com)
There are two kinds of comments in C++(www.cppentry.com): 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 programbut 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 pairsgenerally are used for multiline explanations, whereas double-slash comments tend to be used for half-line and single-line remarks:
- #include <iostream>
-
-
-
-
- int main()
- {
-
- std::cout << "Enter two numbers:" << std::endl;
- int v1 = 0, v2 = 0;
- std::cin >> v1 >> v2;
- std::cout << "The sum of " << v1 << " and " << v2
- << " is " << v1 + v2 << std::endl;
- return 0;
- }
In this book, we italicize comments to make them stand out from the normal program text. In actual programs, whether comment text is distinguished from the text used for program code depends on the sophistication of the programming environment you are using.