Declared Constants (Advanced)

Top  Previous  Next

Names can also be declared for constants. Constants are different from variables because once they are defined they cannot be changed. Using a constant is more efficient than using a variable. Giving names to numbers can add clarity to a program. For instance, the name "Highest" might be more meaningful than the number 29028.

 

Declared constants have the form:

 

        define NAME = CONSTANT, ... NAME = CONSTANT;

 

For example:

 

        define Summit = 14210, Highest = 29028, Median = 13489.72;

 

In this example Summit and Highest are integer constants, and Median is a real constant.

 

Any constant can be used in a "define", for example:

 

        define A = $41, B = 66, C = -^C, LETTER = B, Number= -3.1E-3;

 

Note that B, once it is defined, can be used to define other constants. Also note that a constant can be signed (- or +).

 

Sometimes it is useful to have distinct names for things, but the actual value is irrelevant. In fact sometimes we do not want to know the value so that we cannot come to depend on it. For example, we might be working with a set of colors that we just want to distinguish by name. If we come to depend on the particular numerical value of a color, later changes in the program might be difficult. XPL0 has a simple scheme for defining sets of things:

 

        define Red, Blue, Green;

 

Here, all you need to know is that these constants have distinct values.

The values actually assigned by the compiler are integers beginning with zero and stepping by one up to the last item in the set. In the example, Red equals 0, Blue equals 1, and Green equals 2.