In matters of grave importance, style, not sincerity, is the vital thing.
OSCAR WILDE, The Importance of Being Earnest
All the variable names in our sample programs were chosen to suggest their use. Our sample programs were laid out in a particular format. For example, the declarations and statements were all indented the same amount. These and other matters of style are of more than aesthetic interest. A program that is written with careful attention to style is easier to read, easier to correct, and easier to change.
A program should be laid out so that elements that are naturally considered a group are made to look like a group. One way to do this is to skip a line between parts that are logically considered separate. Indenting can also help to make the structure of the program clearer. A statement within a statement should be indented. In particular, if-else
statements, while
loops, and do-while
loops should be indented either as in our sample programs or in some similar manner.
The braces {}
determine a large part of the structure of a program. Placing each brace on a line by itself, as we have been doing, makes it easy to find the matching pairs. Notice that we have indented some pairs of braces. When one pair of braces is embedded in another pair, the embedded braces are indented more than the outer braces. Look back at the program in Display 2.16. The braces for the body of the while
loop are indented more than the braces for the main
part of the program.
There are at least two schools of thought on where you should place braces. The first, which we use in this book, is to reserve a separate line for each brace. This form is easiest to read. The second school of thought holds that the opening brace for a pair need not be on a line by itself. If used with care, this second method can be effective, and it does save space. The important point is to use a style that shows the structure of the program. The exact layout is not precisely dictated, but you should be consistent within any one program.
In order to make a program understandable, you should include some explanatory notes at key places in the program. Such notes are called comments. C++ and most other programming languages have provisions for including such comments within the text of a program. In C++ the symbols //
are used to indicate the start of a comment. All of the text between the //
and the end of the line is a comment. The compiler simply ignores anything that follows //
on a line. If you want a comment that covers more than one line, place a //
on each line of the comment. The symbols //
are two slashes (without a space between them).
In this book, comments will always be written in italic so that they stand out from the program text. Some text editors indicate comments by showing them in a different color from the rest of the program text.
There is another way to insert comments in a C++ program. Anything between the symbol pair /*
and the symbol pair */
is considered a comment and is ignored by the compiler. Unlike the //
comments, which require an additional //
on each line, the /*
to */
comments can span several lines, like so:
/*This is a comment that spans three lines. Note that there is no comment symbol of any kind on the second line.*/
Comments of the /* */
type may be inserted anywhere in a program that a space or line break is allowed. However, they should not be inserted anywhere except where they are easy to read and do not distract from the layout of the program. Usually, comments are only placed at the ends of lines or on separate lines by themselves.
There are differing opinions on which kind of comment is best to use. Either variety (the //
kind or the /* */
kind) can be effective if used with care. We will use the //
kind in this book.
It is difficult to say just how many comments a program should contain. The only correct answer is “just enough,” which of course conveys little to the novice programmer. It will take some experience to get a feel for when it is best to include a comment. Whenever something is important and not obvious, it merits a comment. However, too many comments are as bad as too few. A program that has a comment on each line will be so buried in comments that the structure of the program is hidden in a sea of obvious observations. Comments like the following contribute nothing to understanding and should not appear in a program:
distance = speed * time; //Computes the distance traveled
Notice the comment given at the start of the program in Display 2.17. All programs should begin with a comment similar to the one shown there. It gives all the essential information about the program: what file the program is in, who wrote the program, how to contact the person who wrote the program, what the program does, the date that the program was last modified, and any other particulars that are appropriate, such as the assignment number, if the program is a class assignment. Exactly what you include in this comment will depend on your particular situation. We will not include such long comments in the programs in the rest of this book, but you should always begin your programs with a similar comment.
There are two problems with numbers in a computer program. The first is that they carry no mnemonic value. For example, when the number 10
is encountered in a program, it gives no hint of its significance. If the program is a banking program, it might be the number of branch offices or the number of teller windows at the main office. In order to understand the program, you need to know the significance of each constant. The second problem is that when a program needs to have some numbers changed, the changing tends to introduce errors. Suppose that 10
occurs twelve times in a banking program, that four of the times it represents the number of branch offices, and that eight of the times it represents the number of teller windows at the main office. When the bank opens a new branch and the program needs to be updated, there is a good chance that some of the 10
s that should be changed to 11
will not be, or some that should not be changed will be. The way to avoid these problems is to name each number and use the name instead of the number within your program. For example, a banking program might have two constants with the names BRANCH_COUNT
and WINDOW_COUNT
. Both these numbers might have a value of 10
, but when the bank opens a new branch, all you need do in order to update the program is to change the definition of BRANCH_COUNT
.
How do you name a number in a C++ program? One way is to initialize a variable to that number value, as in the following example:
int BRANCH_COUNT = 10;
int WINDOW_COUNT = 10;
There is, however, one problem with this method of naming number constants: You might inadvertently change the value of one of these variables. C++ provides a way of marking an initialized variable so that it cannot be changed. If your program tries to change one of these variables, it produces an error condition. To mark a variable declaration so that the value of the variable cannot be changed, precede the declaration with the word const
(which is an abbreviation of constant). For example:
const int BRANCH_COUNT = 10;
const int WINDOW_COUNT = 10;
If the variables are of the same type, it is possible to combine the previous lines into one declaration, as follows:
const int BRANCH_COUNT = 10, WINDOW_COUNT = 10;
However, most programmers find that placing each name definition on a separate line is clearer. The word const
is often called a modifier, because it modifies (restricts) the variables being declared.
A variable declared using the const
modifier is often called a named constant. Writing named constants in all uppercase letters is not required by the C++ language, but it is standard practice among C++ programmers. The actual constant value, 10 in the above example, is called a literal constant.
Once a number has been named in this way, the name can then be used anywhere the number is allowed, and it will have exactly the same meaning as the number it names. To change a named constant, you need change only the initializing value in the const
variable declaration. The meaning of all occurrences of BRANCH_COUNT
, for instance, can be changed from 10
to 11
simply by changing the initializing value of 10
in the declaration of BRANCH_COUNT
.
Although unnamed numeric constants are allowed in a program, you should seldom use them. It often makes sense to use unnamed number constants for well-known, easily recognizable, and unchangeable quantities, such as 100 for the number of centimeters in a meter. However, all other numeric constants should be given names in the fashion we just described. This will make your programs easier to read and easier to change.
Display 2.17 contains a simple program that illustrates the use of the declaration modifier const
.
The following if-else
statement will compile and run without any problems. However, it is not laid out in a way that is consistent with the other if-else
statements we have used in our programs. Rewrite it so that the layout (indenting and line breaks) matches the style we used in this chapter.
if (x < 0) {x = 7; cout << "x is now positive.";}
else {x = − 7; cout << "x is now negative.";}
What output would be produced by the following two lines (when embedded in a complete and correct program)?
//cout << "Hello from"; cout << "Self-Test Exercise";
Write a complete C++ program that asks the user for a number of gallons and then outputs the equivalent number of liters. There are 3.78533 liters in a gallon. Use a declared constant. Since this is just an exercise, you need not have any comments in your program.