Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: Pascal
Expertise: Beginner
May 28, 1997



Application Security Testing: An Integral Part of DevOps

Variant Records: The equivalent to the C-union structure

Is there a way to create a C 'union'-like structure in Delphi? That is, a structure that uses the same memory area?

The Delphi (Pascal/ObjectPascal) equivalent to a C-union structure is called a Variant Record (not to be confused with the Variant "type" available in Delphi 2.0+). As with a C-union, the Pascal variant record allows several structure types to be combined into one, and all will occupy the same memory space. Look up the syntax declaration under "Records" in the help file. But here's an example:

 TPerson = record
   FirstName, LastName: string[40];
   BirthDate: TDate;
   case Citizen: Boolean of
     True: (BirthPlace: string[40]);
     False: (Country: string[20];
       EntryPort: string[20];
       EntryDate: TDate;
       ExitDate: TDate);
The record above is actually a single expression of two records that could describe a person:
 TPersonCitizen = record
   FirstName, LastName: string[40];
   BirthDate: TDate;
   BirthPlace: string[40]
 TPersonAlien = record
   FirstName, LastName: string[40];
   BirthDate: TDate;
   Country: string[20];
   EntryPort: string[20];
   EntryDate: TDate;
   ExitDate: TDate;
And as in a union, the combination of the two types of records makes for much more efficient programming, because a person could be expressed in a variety of ways.

Everything I explained above is pretty hypothetical stuff. In Delphi, the TRect structure that describes a rectangle is actually a variant record:

TPoint = record
  X: Longint;
  Y: Longint;

TRect = record
  case Integer of
    0: (Left, Top, Right, Bottom: Integer);
    1: (TopLeft, BottomRight: TPoint);
where the coordinates of the rectangle can be expressed using either four integer values or two TPoints.

I realize this is pretty quick and dirty, so I suggest you refer to the help file for a more in-depth explanation, or go to your nearest book store or library and look at any Pascal book (not Delphi -- most won't explain this fairly esoteric structure). However, if you're familiar with the C-union, this stuff should be an absolute breeze.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date