[ < ] | [ > ] |  | [ << ] | [ Up ] | [ >> ] |  |  |  |  | [Top] | [Contents] | [Index] | [ ? ]

### 4.4.2 Overlaying strings in variant records

Q: Should the different variants in a variant record overlay in the same memory? Previous Pascals I have used have guaranteed this, and I've got low-level code that relies on this. The variants are not the same length, and they are intended not to be.

A: No, this is intentional so that the discriminants are not overwritten, and they can be properly initialized in the first place. Consider:

    record
    case Boolean of
      False: (s1: String (42));
      True:  (s2: String (99));
    end;

If the strings would overlay, in particular their discriminants would occupy the same place in memory. How should it be initialized? Either way, it would be wrong for at least one of the variants ...

So, after a discussion in comp.lang.pascal.ansi-iso where this topic came up concerning file variables (which also require some automatic initialization and finalization), we decided to do this in GPC for all types with automatic initialization and finalization (currently files and schemata, in the future this might also be Delphi compatible classes and user-defined initialized and finalized types), since the standard does not guarantee variants to overlay, anyway ...

There are two ways in GPC to get guaranteed overlaying (both non-standard, of course, since the standard does not assume anything about internal representations; both BP compatible), ``absolute'` declarations and variable type casts. E.g., in order to overlay a byte array ``b'` to a variable ``v'`:

    var
      b: array [1 .. SizeOf (v)] of Byte absolute v;

Or you can use type-casting:

    type
      t = array [1 .. SizeOf (v)] of Byte;

then ``t (v)'` can be used as a byte array overlayed to ``v'`.

This document was generated by Frank Heckenbach on May, 10 2002 using texi2html