Home Up Contents Search

Records

Records are a structured type consisting of collections of objects of other types. A record variable can be used as a whole, or its
individual components, called fields, can be used individually.

The syntax for a record declaration is shown here:

RecType = record
<field1>: <sometype>;
<field2>: <sometype>;
.
.
.
<fieldn>: <someType>;
end;


Once a variable of a record type has been declared, you can assign information to one of its fields by writing the name of the variable, a period, and then the field name. In general, a field of a record can be used wherever a variable of the field's type would be acceptable. For example:

type

student = record

name: string[40];
age: integer;
GPA: real;
major: ( music, english, history, science );

end;


var S : student;

begin

S.name := "Susan Carlson";
S.age := 19;
S.GPA := 3.41;
S.major := english;

end.


The WITH statement is a shorthand notation for accessing the fields of a record; inside a WITH statement (which may include a begin/end block), the name of the record is unnecessary to access its fields. For example, the previous assignments to record variable S could have been written as:

begin

with S do

begin

name := 'Susan Carlson';
age := 19;
GPA := 3.41;
major := english;

end;

end.



Variant Records
A variant record is a special form of record in which some or all of the fields are given overlapping storage in memory. This allows an application to conserve memory when many of a record's fields are inappropriate for a particular class of object being stored.

For example, a record that represents a transaction in a department store can have separate fields according to the method of purchase; one for cheques, and another for credit cards.

type
paymentType = ( cash, cheque, credit );

purchase =
record

Amount : currency;
Date :
string[8];
case payMethod : paymentType of
cash : ( );
cheque : (chequeNo : integer; licenseNumber: longint );
credit: (cardNo : longint; expiration:
string[8]);

end;



The variant part of the record definition must come at the end.

program RecordExample;

type

cheque = record

number: integer;
amount: currency;
date: array [1..8] of char;
{ '99/99/99' }
payee:
string[40];

end;


var

MyCheque : cheque;
YourCheque: cheque;

begin

MyCheque.number := 753; { Christmas present }
MyCheque.amount := 87000000.00;
MyCheque.date := '12/25/88';
MyCheque.payee := 'Myself';

YourCheque := MyCheque;
{ all fields assigned automatically }

YourCheque.number := YourCheque.number + 1;
with YourCheque do

begin

Writeln('Amount = ',amount);
Writeln('Date = ',date);

end;

end. { RecordExample }

 
 
Previous Next
Send mail to ljschwerin@hotmail.com with questions or comments about this web site.

Copyright © 1999-2002 Leon Schwerin
Last modified: 26 March 2000
1