Out-of-range error

advertisement
Out-of-range error
• An out-of-range error is when you try to
access an element of an array that is outside
the range indicated in the declaration.
• When using arrays, the compiler may not
pick up on an out-of-range error.
Difference between TYPE and
VAR
• TYPE declares a new type that you can use
in the VAR section.
• VAR declares a new variable of a certain
type. It can be a predefined type (integer,
char, etc.) or a user defined type (MyArray)
Placement of type definition
• In Turbo Pascal, the TYPE definition can be
placed before or after the CONST definition
and the VAR declaration unless an item in
one of these depends on a definition in the
others.
CONST MaxSubscr = 20;
TYPE IntArray = ARRAY [1..MaxSubsc] OF integer;
VAR MarkArray: IntArray;
Declaring an array without a type
statement
• You can declare an array in the VAR
section:
VAR MyArray: ARRAY[1..10] OF Char;
• If you do so, you do not define a reusable
type, but only the dimensions of a particular
variable. In other words you cannot now
declare 3 or 4 variables of type MyArray.
Examples of legal arrays
• An array of integers with character subscripts:
TYPE CharArray = ARRAY[‘a’..’z’] OF integer;
• An array of characters with integer subscripts:
TYPE IntArray = ARRAY[-10..10] OF char:
• An array of reals with Boolean subscripts:
TYPE RealArray = ARRAY[false..true] OF real;
• reals can not be subscripts because they are not an
ordinal type.
Arrays and the watch window
Initializing arrays
• In order to initialize an array, you must use
a loop (or explicitly initialize each element
of the array)
FOR Index := 1 TO 10 DO
MyArray[Index] := 0;
• Note: In the case of integers, Turbo Pascal
would automatically initialize the values to
0 but other Pascal compilers may not.
an array of chars vs. a string
• An array of characters is very similar to a
string. The biggest difference is the first
byte of a string contains the length of that
string (remember I said the maximum
length is 255 characters)
• You can access components of a string the
way you would an array.
Typed CONST
• Typed constants can be changed. For
example, with the following definition:
CONST Days: ARRAY [1..7] OF string =
(‘Sun’, ‘Mon’, ‘Tues’, ‘Wed’, ‘Thurs’,
‘Fri’, ‘Sat’);
• You can change ‘Mon’ to ‘Monday’ by
Days[2] := ‘Monday’;
Download