Next: , Previous: String schema, Up: Strings in GPC

3.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:

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

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 the ISO Pascal newsgroup 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, objects and schemata, including strings, 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:

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

Or you can use type-casting:

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

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