A hidden feature of $POINTERMATH directive in Delphi 2009

The $POINTERMATH directive (introduced in Delphi 2009) allows to treat a typed pointer as a scaled ordinal or as an array. Here is a code sample that wouldn’t compile without $POINTERMATH turned ON

{$POINTERMATH ON}
procedure TForm1.Button1Click(Sender: TObject);
var
  P, P1: PInteger;
  N: Integer;

begin
  P:= @Self;
  N:= 2;
  P1:= P + N;           // treats P as a scaled ordinal
  N:= P[N];             // treats P as an array
  ShowMessage(Format('%p -- %p -- %d', [P, P1, N]));
end;

But the following code is also OK, though $POINTERMATH is turned OFF:

{$POINTERMATH OFF}
procedure TForm1.Button1Click(Sender: TObject);
var
  P, P1: PByte;
  N: Integer;

begin
  P:= @Self;
  N:= 2;
  P1:= P + N;           // treats P as a scaled ordinal
  N:= P[N];             // treats P as an array
  ShowMessage(Format('%p -- %p -- %d', [P, P1, N]));
end;

So the byte pointers (PByte type) ignore $POINTERMATH settings. Pointer arithmetics is always enabled for pointers into bytes [at least in Delphi 2009, can’t say about future versions], like it was enabled for PChar type in old pre-unicode Delphi versions.

Advertisements

2 thoughts on “A hidden feature of $POINTERMATH directive in Delphi 2009

  1. PByte is just compiled with the directive turned on I believe, so it’s not that it ‘ignores’ it as such (System.pas should tell all…)

    By the by, how about adding a link to DelphiFeeds.com and getting your blog listed there?

    • Yes, thank you, Ctrl+LeftClick on PByte in source code editor moves you to PByte declaration in System.pas and immediately explains the feature.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s