Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delphi assign to const?

this site : http://www.drbob42.com/delphi/wizards.htm

showed a very puzzling code at the bottom

 unit ShareMem;
 { (c) 1997 by Bob Swart (aka Dr.Bob - http://www.drbob42.com }
 interface

 const
...
 uses
   Windows;

 const
   Handle: THandle = 0;
...
 function GetCommandLine: PChar; stdcall;
   external 'kernel32.dll' name 'GetCommandLineA';
...
   begin
     Handle := LoadLibrary('BCBMM.DLL');
 end.

how could this be ?

like image 315
none Avatar asked Nov 02 '25 15:11

none


2 Answers

Delphi has something called assignable consts which allows a const value to be assigned. This can be turned on/off through compiler directives and switches. For a longer answer see here.

It sometimes comes in handy in times before class properties were possible. Even if the const is declared inside a function, it keeps its value between calls.

procedure Test;
{$WRITEABLECONST ON}
const
  AssignableConst: Integer = 0;
{$WRITEABLECONST OFF}
begin
  AssignableConst := AssignableConst + 1; 
  WriteLn('Test is called ' + IntToStr(AssignableConst) + ' times'); 
end;
like image 194
Lars Truijens Avatar answered Nov 04 '25 08:11

Lars Truijens


A typed const, by default (Edit: as noted by Rob in comments, this was changed to no longer be the default years ago), is more like a static variable. You can turn this behavior off with a compiler directive.

This was commonly used as a substitute for class/static properties in old versions of Delphi. Now that Delphi actually has that feature, there is no good reason to do this IMHO.

like image 44
Craig Stuntz Avatar answered Nov 04 '25 07:11

Craig Stuntz