DelphiBasics
$Align
Compiler Directive
Determines whether data is aligned or packed
1   {$Align Off}
2   {$Align On}
Description
The $Align compiler directive determines whether Delphi aligns data, or whether it packs the data into the smallest space.
 
With $Align On (default), complex data types, such as records have their elements aligned to 2, 4 or 8 byte boundaries, as appropriate to the data type. For example, a Word field would be aligned to a 2 byte boundary.
 
With $Align On, the default value, you can override this setting with the packed option for complex data structures.
 
These alignments ensure optimal access performance.
 
$Align Off tells Delphi to ignore alignment, and thereby pack data.
Notes
Examples of unpacked alignments :

Word     = 2 bytes

LongWord = 4 bytes

Single   = 4 bytes

Double   = 8 bytes

$Align is equivalent to $A.

This directive can be used multiple times within your code.

The default value is $Align On
Related commands
$A Determines whether data is aligned or packed
Packed Compacts complex data types into minimal storage
 Author links

 Download this web site as a Windows program.





 
Example code : Packing a record to reduce storage
// Full Unit code.
// -----------------------------------------------------------
// You must store this code in a unit called Unit1 with a form
// called Form1 that has an OnCreate event called FormCreate.
 
unit Unit1;
 
interface
 
uses
  SysUtils,
  Forms, Dialogs;
 
type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  end;
 
var
  
Form1: TForm1;
 
implementation
{$R *.dfm} // Include form definitions
 
procedure TForm1.FormCreate(Sender: TObject);

type
  // Use the default setting : $Align+
  // Declare an unpacked, aligned record
  TAlignedRecord = Record
    name1   : string[4];
    floater : single;
    name2   : char;
    int     : Integer;
  end;

  // Declare a packed record
  TPackedRecord = Packed Record
    name1   : string[4];
    floater : single;
    name2   : char;
    int     : Integer;
  end;

  // Set alignment off
  {$Align Off}

  // Declare an unpacked record
  // This will get treated as if packed was on
  TUnPackedRecord = Record
    name1   : string[4];
    floater : single;
    name2   : char;
    int     : Integer;
  end;

var
  alignedRec  : TAlignedRecord;
  packedRec   : TPackedRecord;
  unPackedRec : TUnPackedRecord;

begin
  ShowMessage('Aligned record size = '+IntToStr(SizeOf(alignedRec)));
  ShowMessage('Packed record size = '+IntToStr(SizeOf(packedRec)));
  ShowMessage('UnPacked record size = '+IntToStr(SizeOf(unPackedRec)));
end;
 
end.
Hide full unit code
   Aligned record size = 20
   Packed record size = 14
   UnPacked record size = 14
 
Delphi Programming Neil Moffatt 2002 - 2020. All rights reserved.  |  Home Page