Sams Teach Yourself C++ in 21 Days

(singke) #1
The Anatomy of a C++ Program 33

2


To fight the onset of bafflement, and to help others understand your code, you need to
use comments. Comments are text that is ignored by the compiler, but that can inform
the reader of what you are doing at any particular point in your program.

Types of Comments ..........................................................................................


C++ comments come in two flavors: single-line comments and multiline comments.
Single-line comments are accomplished using a double slash (//). The double slash tells
the compiler to ignore everything that follows, until the end of the line.
Multiline comments are started by using a forward slash followed by an asterisk (/*). This
“slash-star” comment mark tells the compiler to ignore everything that follows until it finds
a star-slash (*/) comment mark. These marks can be on the same line or they can have one
or more lines between them; however, every /*must be matched with a closing */.
Many C++ programmers use the double-slash, single-line comments most of the time
and reserve multiline comments for blocking out large blocks of a program. You can
include single-line comments within a block “commented out” by the multiline comment
marks; everything, including the double-slash comments, are ignored between the multi-
line comment marks.

The multiline comment style has been referred to as C-style because it was
introduced and used in the C programming language. The single-line com-
ments were originally a part of C++ and not a part of C; thus, they have
been referred to as C++-style. The current standards for both C and C++ now
include both styles of comments.

NOTE


Using Comments ..............................................................................................


Some people recommend writing comments at the top of each function, explaining what
the function does and what values it returns.
Functions should be named so that little ambiguity exists about what they do, and con-
fusing and obscure bits of code should be redesigned and rewritten so as to be self-
evident. Comments should not be used as an excuse for obscurity in your code.
This is not to suggest that comments ought never be used, only that they should not be
relied upon to clarify obscure code; instead, fix the code. In short, you should write your
code well, and use comments to supplement understanding.
Listing 2.5 demonstrates the use of comments, showing that they do not affect the pro-
cessing of the program or its output.
Free download pdf