User Tools

Site Tools


guides:programstyle:constants

Constants

If a constant used in a program has a meaning, or it is possible that this constant may be changed in the future, the constant should be named. In general there should be no magic numbers or numbers that have a meaning but are not named, in a program.

Assume you are writing a program involving sales tax. The county tax rate is fixed at 4.75%. This rate will not change for the duration of the program, but in the future the tax rate may change, so this should be a named constant.

Acceptable Example

const float TAX_RATE = 0.0475;
...
 
tax = price * TAX_RATE;

Unacceptable Example:

tax = price * 0.0475;

At times the same constant may be given multiple names. Assume you are writing a program where the maximum number of items a person may purchase is 20. In addition, if the purchase price is over $20, the consumer will receive a discount. Each of these has a different meaning, so each should be declared as a named constant.

Acceptable Example:

const int MAX_ITEMS  = 20;
const int PRICE_BREAK = 20;
 
...
 
if (itemCount > MAX_ITEMS) {
 ...
}
 
if (price > PRICE_BREAK) {
    // the price was over $20, so give the customer a discount 
}

Unacceptable Example:

const int MAX_ITEMS = 20;
 
if (price > MAX_ITEMS) {
    // the price was over $20, so give the customer a discount
   ...
}

Note this is a very bad use. If the user decided to change MAX_ITEMS, a new bug would be introduced into the code.

In the last example, a programmer might be tempted to employ the following definition

const int TWENTY = 20;

This is unacceptable for multiple reasons.

  • TWENTY is no more informative than 20.
  • If the value of the constant changed, the programmer might be tempted to produce the following totally unacceptable code
  • const int TWENTY = 35;

Unless otherwise instructed, single use constants are usually not named unless they provide clarity to the program. Examples include a prompt used one time or an arbitrary field width.

The following is probably not necessairy

const int FIRST_FIELD_WITDTH = 20;
const string FIRST_PROMPT = "Enter your Age";
...
 
cout << setw(FIRST_FIELD_WIDTH) << FIRST_PROMPT << endl;
guides/programstyle/constants.txt · Last modified: 2024/07/25 15:01 by 127.0.0.1