Next: General form of a Up: A simple C++ program Previous: Declaration of variables

Constants and the declaration of constants

Often in programming numerical constants are used, e.g. the value of $\pi$. It is well worthwhile to associate meaningful names with constants. These names can be associated with the appropriate numerical value in a constant declaration. The names given to constants must conform to the rules for the formation of identifiers as defined above. The following constant declaration

const int days_in_year = 365;
defines an integer constant days_in_year which has the value 365. Later in the program the identifier days_in_year can be used instead of the integer 365, making the program far more readable.

The general form of a constant declaration is:

const type constant-identifier = value ;
type is the type of the constant, constant-identifier is the identifier chosen for the constant, which must be distinct from all identifiers for variables, and value is an expression involving only constant quantities that gives the constant its value. It is not possible to declare a constant without giving it an initial value.

Another advantage of using constant declarations is illustrated by the following declaration:

const float VatRate = 17.5;
This defines a constant VatRate to have the value 17.5, however if the Government later changes this rate then instead of having to search through the program for every occurrence of the VAT rate all that needs to be done is to change the value of the constant identifier VatRate at the one place in the program. This of course only works if the constant identifier VatRate has been used throughout the program and its numeric equivalent has never been used.

Constant definitions are, by convention, usually placed before variable declarations. There is no limit on how many constant declarations can be used in a program. Several constant identifiers of the same type can be declared in the same constant declaration by separating each declaration by a comma. Thus

const int days_in_year = 365,
          days_in_leap_year = 366;
Note that it is illegal in C++ to attempt to change the value of a constant.



Next: General form of a Up: A simple C++ program Previous: Declaration of variables