I l@ve RuBoard Previous Section Next Section

5.9 Constant and Reference Declarations

Sometimes you want to use a value that does not change, such as figs/U03C0.gif. The keyword const indicates a variable that never changes. To declare a value for pi, we use the statement:

const float PI = 3.1415926;    // The classic circle constant

By convention variable names use lowercase only while constants use uppercase only. However, there is nothing in the language that requires this, and some programming projects use a different convention.

In fact, there are major programming environments such as the X Windows System that use their own naming conventions with mixed-case constants and variables (VisibilityChangeMask, XtConvertAndStore, etc.). The Microsoft Windows API also uses its own unique naming convention.

Constants must be initialized at declaration time and can never be changed. For example, if we tried to reset the value of PI to 3.0 we would generate an error message:

PI = 3.0;      // Illegal

Integer constants can be used as a size parameter when declaring an array:

const int TOTAL_MAX = 50;    // Max. number of elements in total list
float total_list[TOTAL_MAX]; // Total values for each category

Another special variable type is the reference type. The following is a typical reference declaration:

int count;                  // Number of items so far
int& actual_count = count;  // Another name for count

The special character & is used to tell C++ that actual_count is a reference. The declaration causes the names count and actual_count to refer to the same variable. For example, the following two statements are equivalent:

count = 5;            // "Actual_count" changes too
actual_count = 5;     // "Count" changes too

In other words, a simple variable declaration declares a box to put data in. A reference variable slaps another name on the box, as illustrated in Figure 5-1.

Figure 5-1. Reference variables
figs/C++2_0501.gif

This form of the reference variable is not very useful. In fact, it is almost never used in actual programming. In Chapter 9, you'll see how another form of the reference variable can be very useful.

    I l@ve RuBoard Previous Section Next Section