Constant Arrays (Advanced)

Top  Previous  Next

Sometimes what we need is a fixed table of values. It is possible to assign values to each element of an array, but a better way is to use a constant array. The general form is:




For example:


        integer Data;


        Data:= [2, 22, 222, 2222, 22222];

      . . .

This array is similar to a text string. The difference is that the elements are 16-bit integer constants instead of 8-bit ASCII characters. In this example, Data(2) contains the value 222. The assignment (:= ) stores the address of the array into Data. The elements of a constant array can be used just like other array elements.


Constant arrays can contain real numbers as well as integers and have multiple dimensions. However, reals and integers cannot both be used in a single array. Here is a 2-dimensional, 3-by-5 array:


        real Data;


        Data:= [[70.0, 70.1, 70.2, 70.3, 70.4],

                [71.0, 71.1, 71.2, 71.3, 71.4],

                [72.0, 72.1, 72.2, 72.3, 72.4]];

        . . .


Data(0,0) contains 70.0, and Data(1,4) contains 71.4. Note that the rows are the first dimension.


A constant array can contain other constant arrays and text strings to make complex data structures. For example:


        Info:= [70, 71, [+720, ^A, [true, -7221] ], $73, "HELLO"];


This array has a structure that looks like this:




Here, Info(0) contains 70, Info(2,0) contains 720, and Info(2,2,0) contains "true". Also, after we store Info(4) into a character variable, we can use it as a character array and access the individual bytes in the string "HELLO". For example:


        character C;

        integer   Info;


        Info:= [70, 71, [+720, ^A, [true, -7221] ], $73, "HELLO"];

        C:= Info(4);

        ChOut(0, C(1));

        . . .


This displays the character "E", and


        Text(0, Info(4));


displays the string "HELLO".


Variables local to a procedure normally do not keep their values from the previous time that the procedure was called. Usually this does not matter, but occasionally the value of a variable is needed the next time the procedure is called. A simple way to code this is to make the variable global. However if the variable is not used by any other procedure, it is best to keep the procedure modular by keeping its variables local. Constant arrays can be used to do this. (Other languages call these "static variables".) Here is an example:


        proc    MakeNumber;

        int     Counter;


        Number:= Ran(100) + 1;

        Counter:= [0];

        Counter(0):= Counter(0) + 1;

        if Counter(0) >= 3 then


                Number:= 50;

                Counter(0):= 0;         \Reset the counter




This procedure sets Number (a global) to 50 every third time it is called. Counter could be declared and initialized in the main procedure, but this way it is kept local to the only procedure that uses it. This makes the overall program more modular and less confusing.