Static Function Variables in Delphi

Delphi doesn’t have the concept of static function variables as you find in languages like C++. However, it is still possible to achieve the same behavior via a compiler directive.

Consider this simple example:

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

procedure Enter;
{$J+}
const
  Count: Integer = 0;

begin
  Inc(Count);
  WriteLn('Entered ' + Count.ToString + ' times');
end;

begin
  Enter;
  Enter;
  Enter;
end.

// output

Entered 1 times
Entered 2 times
Entered 3 times

The {$J+} directive instructs the compiler to allow the constant to be written to, as described here.

For more information on compiler directions, see here.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s