|
|
|
|
|
|
|
const char BLANK = ;
const float PI = 3.14159;
const float INTEREST_RATE = 0.12;
const float TAX_RATE = 0.001;
const int MAX = 20; |
|
|
|
|
|
|
|
|
Many C++ programmers capitalize the entire identifier of a named constant and separate the English words with an underscore. The idea is to let the reader quickly distinguish between variable names and constant names in the middle of a program. |
|
|
|
| | |
|
|
|
|
It's a good idea to use named constants instead of literals. In addition to making your program more readable, it can make it easier to modify. Suppose you wrote a program last year to compute taxes. In several places you used the literal 0.05, which was the sales tax rate at the time. Now the rate has gone up to 0.06. To change your program, you have to locate every literal 0.05 and change it to 0.06. And if 0.05 is used for some other reasonto compute deductions, for exampleyou have to look at each place where it is used, figure out what it is used for, and then decide whether it needs to be changed. |
|
|
|
| |
|
|
|
|
The process is much simpler if you use a named constant. Instead of using a literal constant, suppose you had declared a named constant, TAX_RATE, with a value of 0.05. To change your program, you would simply change the declaration, setting TAX_RATE equal to 0.06. This one modification changes all of the tax rate computations without affecting the other places where 0.05 is used. |
|
|
|
| |
|
|
|
|
C++ allows us to declare constants with different names but the same value. If a value has different meanings in different parts of a program, it makes sense to declare and use a constant with an appropriate name for each meaning. |
|
|
|
| |
|
|
|
|
Named constants also are reliable; they protect us from mistakes. If you mistype the name PI as PO, the C++ compiler will tell you that the name PO has not been declared. On the other hand, even though we recognize that the number 3.14149 is a mistyped version of pi (3.14159), the number is perfectly acceptable to the compiler. It won't warn us that anything is wrong. |
|
|
|
|
|
|
|
|
|
It's a good idea to add comments to constant declarations as well as variable declarations. In the Payroll program we describe in comments what each constant represents: |
|
|
|
|
|