next up previous contents index
Next: Set types Up: Data types Previous: Procedural types

Records

Free Pascal supports records. The prototype type definition of a record is:

Type
  RecType = Record
    Element1 : type1;
    Element2,Element3 : type2;
    ...
    Elementn ; Typen;
  end;
Variant records are also supported:
Type
  RecType = Record
    Element1 : type1;
    Case [PivotElmt:] Type Identifier of
      Value1 : (VarElt1, Varelt2 : Vartype1);
      Value2 : (VarElt3, Varelt4 : Vartype2);
  end;
The variant part must be last in the record. The optional PivotElmt can be used to see which variant is active at a certain time.

Remark: If you want to read a typed file with records, produced by a Turbo Pascal program, then chances are that you will not succeed in reading that file correctly.

The reason for this is that by default, elements of a record are aligned at 2-byte boundaries, for performance reasons. This default behaviour can be changed with the {$PackRecords n} switch. Possible values for n are 1, 2 and 4. This switch tells the compiler to align elements of a record or object or class on 1,2 or 4 byte boundaries.

Take a look at the following program:

Program PackRecordsDemo;

type {$PackRecords 2}
     Trec1 = Record
       A : byte;
       B : Word;
       
     end;
     
     {$PACKRECORDS 1}
     Trec2 = Record
       A : Byte;
       B : Word;
       end;

begin
  Writeln ('Size Trec1 : ',SizeOf(Trec1));
  Writeln ('Size Trec2 : ',SizeOf(Trec2));
end.

The output of this program will be :

Size Trec1 : 4
Size Trec2 : 3
And this is as expected. In Trec1, each of the elements A and B takes 2 bytes of memory, and in Trec1, A takes only 1 byte of memory.

Remark: As from version 0.9.3 (a developers' version), Free Pascal supports also the 'packed record', this is a record where all the elements are byte-aligned.

Thus the two following declarations are equivalent:

     {$PACKRECORDS 1}
     Trec2 = Record
       A : Byte;
       B : Word;
       end;
     {$PACKRECORDS 2}
and
     Trec2 = Packed Record
       A : Byte;
       B : Word;
       end;
Note the {$PACKRECORDS 2} after the first declaration !



Michael Van Canneyt
Thu Sep 10 14:02:43 CEST 1998